{ "version": 3, "sources": ["../../../../node_modules/immer/src/utils/errors.ts", "../../../../node_modules/immer/src/utils/common.ts", "../../../../node_modules/immer/src/utils/plugins.ts", "../../../../node_modules/immer/src/core/scope.ts", "../../../../node_modules/immer/src/core/finalize.ts", "../../../../node_modules/immer/src/core/proxy.ts", "../../../../node_modules/immer/src/core/immerClass.ts", "../../../../node_modules/immer/src/core/current.ts", "../../../../node_modules/immer/src/plugins/es5.ts", "../../../../node_modules/immer/src/plugins/patches.ts", "../../../../node_modules/immer/src/plugins/mapset.ts", "../../../../node_modules/immer/src/plugins/all.ts", "../../../../node_modules/immer/src/immer.ts", "../../../../node_modules/immer/src/utils/env.ts", "../../../../bundles/core/src/NextLotJSDATA.ts", "../../../../bundles/core/src/type_defs/api.ts", "../../../../bundles/core/src/StaticModelsAndConstants.ts", "../../../../node_modules/react/cjs/react.production.min.js", "../../../../node_modules/react/index.js", "../../../../node_modules/scheduler/cjs/scheduler.production.min.js", "../../../../node_modules/scheduler/index.js", "../../../../node_modules/react-dom/cjs/react-dom.production.min.js", "../../../../node_modules/react-dom/index.js", "../../../../node_modules/react-dom/client.js", "../../../../node_modules/use-sync-external-store/cjs/use-sync-external-store-shim.production.min.js", "../../../../node_modules/use-sync-external-store/shim/index.js", "../../../../node_modules/use-sync-external-store/cjs/use-sync-external-store-shim/with-selector.production.min.js", "../../../../node_modules/use-sync-external-store/shim/with-selector.js", "../../../../node_modules/react-redux/es/utils/reactBatchedUpdates.js", "../../../../node_modules/react-redux/es/utils/batch.js", "../../../../node_modules/react-redux/es/components/Context.js", "../../../../node_modules/react-redux/es/hooks/useReduxContext.js", "../../../../node_modules/react-redux/es/utils/useSyncExternalStore.js", "../../../../node_modules/react-redux/es/hooks/useSelector.js", "../../../../node_modules/react-redux/node_modules/@babel/runtime/helpers/esm/extends.js", "../../../../node_modules/react-redux/node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js", "../../../../node_modules/react-is/cjs/react-is.production.min.js", "../../../../node_modules/react-is/index.js", "../../../../node_modules/hoist-non-react-statics/dist/hoist-non-react-statics.cjs.js", "../../../../node_modules/react-redux/node_modules/react-is/cjs/react-is.production.min.js", "../../../../node_modules/react-redux/node_modules/react-is/index.js", "../../../../node_modules/react-redux/es/utils/warning.js", "../../../../node_modules/react-redux/es/connect/verifySubselectors.js", "../../../../node_modules/react-redux/es/connect/selectorFactory.js", "../../../../node_modules/react-redux/es/utils/bindActionCreators.js", "../../../../node_modules/react-redux/es/utils/isPlainObject.js", "../../../../node_modules/react-redux/es/utils/verifyPlainObject.js", "../../../../node_modules/react-redux/es/connect/wrapMapToProps.js", "../../../../node_modules/react-redux/es/connect/invalidArgFactory.js", "../../../../node_modules/react-redux/es/connect/mapDispatchToProps.js", "../../../../node_modules/react-redux/es/connect/mapStateToProps.js", "../../../../node_modules/react-redux/es/connect/mergeProps.js", "../../../../node_modules/react-redux/es/utils/Subscription.js", "../../../../node_modules/react-redux/es/utils/useIsomorphicLayoutEffect.js", "../../../../node_modules/react-redux/es/utils/shallowEqual.js", "../../../../node_modules/react-redux/es/components/connect.js", "../../../../node_modules/react-redux/es/components/Provider.js", "../../../../node_modules/react-redux/es/hooks/useStore.js", "../../../../node_modules/react-redux/es/hooks/useDispatch.js", "../../../../node_modules/react-redux/es/types.js", "../../../../node_modules/react-redux/es/exports.js", "../../../../node_modules/react-redux/es/index.js", "../../../../node_modules/react/cjs/react-jsx-runtime.production.min.js", "../../../../node_modules/react/jsx-runtime.js", "../../../../bundles/apps/webcast/src/components/clerk/ClerkBiddersListTabContentCmp.tsx", "../../../../node_modules/luxon/src/errors.js", "../../../../node_modules/luxon/src/impl/formats.js", "../../../../node_modules/luxon/src/zone.js", "../../../../node_modules/luxon/src/zones/systemZone.js", "../../../../node_modules/luxon/src/zones/IANAZone.js", "../../../../node_modules/luxon/src/impl/locale.js", "../../../../node_modules/luxon/src/zones/fixedOffsetZone.js", "../../../../node_modules/luxon/src/zones/invalidZone.js", "../../../../node_modules/luxon/src/impl/zoneUtil.js", "../../../../node_modules/luxon/src/impl/digits.js", "../../../../node_modules/luxon/src/settings.js", "../../../../node_modules/luxon/src/impl/invalid.js", "../../../../node_modules/luxon/src/impl/conversions.js", "../../../../node_modules/luxon/src/impl/util.js", "../../../../node_modules/luxon/src/impl/english.js", "../../../../node_modules/luxon/src/impl/formatter.js", "../../../../node_modules/luxon/src/impl/regexParser.js", "../../../../node_modules/luxon/src/duration.js", "../../../../node_modules/luxon/src/interval.js", "../../../../node_modules/luxon/src/info.js", "../../../../node_modules/luxon/src/impl/diff.js", "../../../../node_modules/luxon/src/impl/tokenParser.js", "../../../../node_modules/luxon/src/datetime.js", "../../../../node_modules/luxon/src/luxon.js", "../../../../node_modules/redux/node_modules/@babel/runtime/helpers/esm/typeof.js", "../../../../node_modules/redux/node_modules/@babel/runtime/helpers/esm/toPrimitive.js", "../../../../node_modules/redux/node_modules/@babel/runtime/helpers/esm/toPropertyKey.js", "../../../../node_modules/redux/node_modules/@babel/runtime/helpers/esm/defineProperty.js", "../../../../node_modules/redux/node_modules/@babel/runtime/helpers/esm/objectSpread2.js", "../../../../node_modules/redux/es/redux.js", "../../../../node_modules/redux-thunk/es/index.js", "../../../../node_modules/@reduxjs/toolkit/src/index.ts", "../../../../node_modules/@reduxjs/toolkit/src/createDraftSafeSelector.ts", "../../../../node_modules/@reduxjs/toolkit/src/configureStore.ts", "../../../../node_modules/@reduxjs/toolkit/src/devtoolsExtension.ts", "../../../../node_modules/@reduxjs/toolkit/src/isPlainObject.ts", "../../../../node_modules/@reduxjs/toolkit/src/getDefaultMiddleware.ts", "../../../../node_modules/@reduxjs/toolkit/src/tsHelpers.ts", "../../../../node_modules/@reduxjs/toolkit/src/createAction.ts", "../../../../node_modules/@reduxjs/toolkit/src/actionCreatorInvariantMiddleware.ts", "../../../../node_modules/@reduxjs/toolkit/src/utils.ts", "../../../../node_modules/@reduxjs/toolkit/src/immutableStateInvariantMiddleware.ts", "../../../../node_modules/@reduxjs/toolkit/src/serializableStateInvariantMiddleware.ts", "../../../../node_modules/@reduxjs/toolkit/src/createReducer.ts", "../../../../node_modules/@reduxjs/toolkit/src/mapBuilders.ts", "../../../../node_modules/@reduxjs/toolkit/src/createSlice.ts", "../../../../node_modules/@reduxjs/toolkit/src/entities/entity_state.ts", "../../../../node_modules/@reduxjs/toolkit/src/entities/state_selectors.ts", "../../../../node_modules/@reduxjs/toolkit/src/entities/state_adapter.ts", "../../../../node_modules/@reduxjs/toolkit/src/entities/utils.ts", "../../../../node_modules/@reduxjs/toolkit/src/entities/unsorted_state_adapter.ts", "../../../../node_modules/@reduxjs/toolkit/src/entities/sorted_state_adapter.ts", "../../../../node_modules/@reduxjs/toolkit/src/entities/create_adapter.ts", "../../../../node_modules/@reduxjs/toolkit/src/nanoid.ts", "../../../../node_modules/@reduxjs/toolkit/src/createAsyncThunk.ts", "../../../../node_modules/@reduxjs/toolkit/src/matchers.ts", "../../../../node_modules/@reduxjs/toolkit/src/listenerMiddleware/utils.ts", "../../../../node_modules/@reduxjs/toolkit/src/listenerMiddleware/exceptions.ts", "../../../../node_modules/@reduxjs/toolkit/src/listenerMiddleware/task.ts", "../../../../node_modules/@reduxjs/toolkit/src/listenerMiddleware/index.ts", "../../../../node_modules/@reduxjs/toolkit/src/autoBatchEnhancer.ts", "../../../../node_modules/@reduxjs/toolkit/dist/redux-toolkit.esm.js", "../../../../bundles/core/src/webcast/redux/actions.ts", "../../../../bundles/apps/webcast/src/components/NetworkAwareBusyOverlayCmp.tsx", "../../../../bundles/core/src/utilities/TaggedLogger.ts", "../../../../bundles/core/src/utilities/EventBus.ts", "../../../../bundles/core/src/utilities/TimerEventsEmitter.ts", "../../../../bundles/core/src/utilities/index.ts", "../../../../node_modules/urijs/src/punycode.js", "../../../../node_modules/urijs/src/IPv6.js", "../../../../node_modules/urijs/src/SecondLevelDomains.js", "../../../../node_modules/urijs/src/URI.js", "../../../../bundles/core/src/webcast/data/WebcastDataDomain.ts", "../../../../bundles/core/src/webcast/redux/webcast/reducerWbsNetworkStatus.ts", "../../../../bundles/core/src/webcast/redux/webcast/reducerWebcastStatus.ts", "../../../../bundles/core/src/webcast/redux/webcast/reducerWebcastAuctionData.ts", "../../../../bundles/core/src/webcast/redux/webcast/reducerWebcastCurrentRound.ts", "../../../../bundles/core/src/webcast/redux/webcast/reducerWebcastCurrentRoundBidding.ts", "../../../../bundles/core/src/webcast/redux/webcast/reducerWebcastParticipants.ts", "../../../../bundles/core/src/webcast/redux/webcast/reducerWebcastChat.ts", "../../../../bundles/core/src/webcast/redux/reducerActiveWebcast.ts", "../../../../bundles/core/src/webcast/services/DataStore.ts", "../../../../node_modules/currency.js/dist/currency.min.js", "../../../../bundles/core/src/services/MoneyHelper.ts", "../../../../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/null.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/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/browser/index.js", "../../../../node_modules/axios/lib/platform/common/utils.js", "../../../../node_modules/axios/lib/platform/index.js", "../../../../node_modules/axios/lib/helpers/toURLEncodedForm.js", "../../../../node_modules/axios/lib/helpers/formDataToJSON.js", "../../../../node_modules/axios/lib/defaults/index.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/parseProtocol.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/helpers/isAbsoluteURL.js", "../../../../node_modules/axios/lib/helpers/combineURLs.js", "../../../../node_modules/axios/lib/core/buildFullPath.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/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/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/spread.js", "../../../../node_modules/axios/lib/helpers/isAxiosError.js", "../../../../node_modules/axios/lib/helpers/HttpStatusCode.js", "../../../../node_modules/axios/lib/axios.js", "../../../../node_modules/axios/index.js", "../../../../bundles/core/src/services/FrontendApiAdapter.ts", "../../../../bundles/core/src/helpers/DataModelHelpers.ts", "../../../../bundles/core/src/helpers/DateTimeHelpers.ts", "../../../../bundles/core/src/helpers/index.ts", "../../../../bundles/core/src/services/ApiDtoConvertors.ts", "../../../../bundles/core/src/services/AppRemoteDataHandler.ts", "../../../../bundles/core/src/webcast/services/AuctionsManager.ts", "../../../../bundles/core/src/webcast/index.ts", "../../../../bundles/apps/webcast/src/components/clerk/ClerkChatTabContentCmp.tsx", "../../../../bundles/apps/webcast/src/components/clerk/ClerkBiddersListAndChatRootCmp.tsx", "../../../../node_modules/classnames/index.js", "../../../../node_modules/agora-rtc-sdk-ng/AgoraRTC_N-production.js", "../../../../bundles/apps/webcast/src/services/AgoraService.ts", "../../../../bundles/apps/webcast/src/components/clerk/ClerkMediaStreamingCmp.tsx", "../../../../bundles/core/src/webcast/hooks.ts", "../../../../bundles/apps/webcast/src/components/clerk/ClerkAuctionInfoHeaderCmp.tsx", "../../../../node_modules/numeral/numeral.js", "../../../../bundles/apps/webcast/src/components/clerk/bidding/ClerkIncrementsButtonsGrid.tsx", "../../../../bundles/apps/webcast/src/components/clerk/bidding/ClerkRoundStartSetOpeningBidCmp.tsx", "../../../../bundles/apps/webcast/src/components/clerk/bidding/ClerkRoundStopButtonsGroup.tsx", "../../../../bundles/apps/webcast/src/components/clerk/NumberDisplay.tsx", "../../../../bundles/apps/webcast/src/components/clerk/bidding/ClerkBiddingEditableNumericDisplayRowCmp.tsx", "../../../../bundles/apps/webcast/src/components/clerk/bidding/ClerkPlaceFloorAndOnlineBidButtonsStack.tsx", "../../../../bundles/apps/webcast/src/components/clerk/bidding/ClerkRoundStartUpdateOpeningBidCmp.tsx", "../../../../bundles/apps/webcast/src/components/clerk/bidding/ClerkRoundBiddingWithBidsReceivedCmp.tsx", "../../../../bundles/apps/webcast/src/components/clerk/bidding/ClerkRoundStopInfoCmp.tsx", "../../../../bundles/apps/webcast/src/components/clerk/bidding/ClerkRoundChoiceLotsSelectConfirmCmp.tsx", "../../../../bundles/apps/webcast/src/components/clerk/bidding/ClerkBiddingAreaLayoutRootCmp.tsx", "../../../../node_modules/memoize-one/dist/memoize-one.esm.js", "../../../../node_modules/react-virtualized-auto-sizer/dist/react-virtualized-auto-sizer.esm.js", "../../../../node_modules/@babel/runtime/helpers/esm/extends.js", "../../../../node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js", "../../../../node_modules/@babel/runtime/helpers/esm/setPrototypeOf.js", "../../../../node_modules/@babel/runtime/helpers/esm/inheritsLoose.js", "../../../../node_modules/react-window/node_modules/memoize-one/dist/memoize-one.esm.js", "../../../../node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js", "../../../../node_modules/react-window/src/timer.js", "../../../../node_modules/react-window/src/domHelpers.js", "../../../../node_modules/react-window/src/createGridComponent.js", "../../../../node_modules/react-window/src/VariableSizeGrid.js", "../../../../node_modules/react-window/src/createListComponent.js", "../../../../node_modules/react-window/src/VariableSizeList.js", "../../../../node_modules/react-window/src/FixedSizeGrid.js", "../../../../node_modules/react-window/src/FixedSizeList.js", "../../../../node_modules/react-window/src/shallowDiffers.js", "../../../../node_modules/react-window/src/areEqual.js", "../../../../node_modules/react-window/src/shouldComponentUpdate.js", "../../../../bundles/apps/webcast/src/components/clerk/ClerkLotsListCmp.tsx", "../../../../bundles/apps/webcast/src/components/clerk/ClerkCurrentRoundCmp.tsx", "../../../../bundles/apps/webcast/src/components/clerk/bidding/ClerkBiddingHistoryCmp.tsx", "../../../../bundles/apps/webcast/src/components/NetworkDisconnectedAlertPanelOverlayCmp.tsx", "../../../../bundles/core/src/AppController.ts", "../../../../bundles/core/src/services/IPusherAdapter.ts", "../../../../bundles/core/src/hooks/AuctionsListHook.ts", "../../../../bundles/core/src/hooks/CurrentAuctionHooks.ts", "../../../../bundles/core/src/hooks/getCurrentBidder.ts", "../../../../bundles/core/src/hooks/CurrentAuctionLotsListHook.ts", "../../../../bundles/core/src/hooks/index.ts", "../../../../node_modules/@rematch/core/src/reduxStore.ts", "../../../../node_modules/@rematch/core/src/validate.ts", "../../../../node_modules/@rematch/core/src/dispatcher.ts", "../../../../node_modules/@rematch/core/src/bag.ts", "../../../../node_modules/@rematch/core/src/rematchStore.ts", "../../../../node_modules/@rematch/core/src/config.ts", "../../../../node_modules/@rematch/core/src/index.ts", "../../../../node_modules/@rematch/immer/src/index.ts", "../../../../bundles/core/src/rematch/models/auctionsListsModel.ts", "../../../../bundles/core/src/rematch/models/helpers/commonHelpers.ts", "../../../../bundles/core/src/rematch/models/helpers/auctionsHelpers.ts", "../../../../bundles/core/src/rematch/models/helpers/index.ts", "../../../../bundles/core/src/rematch/models/currentAuctionModel.ts", "../../../../bundles/core/src/rematch/models/currentAuctionLotsModel.ts", "../../../../node_modules/lodash/lodash.js", "../../../../bundles/core/src/rematch/models/watchlistModel.ts", "../../../../bundles/core/src/rematch/models/index.ts", "../../../../bundles/core/src/rematch/store.ts", "../../../../bundles/core/src/index.ts", "../../../../bundles/apps/webcast/src/components/WebcastPageFooterLineCmp.tsx", "../../../../bundles/apps/webcast/src/components/clerk/ClerkCurrentRoundHighestOnlineBidsCmp.tsx", "../../../../bundles/apps/webcast/src/components/clerk/ClerkClosedRoundsCmp.tsx", "../../../../bundles/core/src/webcast/hooks/useWebcastConnect.ts", "../../../../bundles/apps/webcast/src/components/clerk/ClerkRootCmp.tsx", "../../../../bundles/apps/webcast/src/screen_clerk.tsx", "../../../../node_modules/prop-types/lib/ReactPropTypesSecret.js", "../../../../node_modules/prop-types/factoryWithThrowingShims.js", "../../../../node_modules/prop-types/index.js", "../../../../node_modules/react-modal/lib/helpers/tabbable.js", "../../../../node_modules/react-modal/lib/helpers/focusManager.js", "../../../../node_modules/react-modal/lib/helpers/scopeTab.js", "../../../../node_modules/warning/warning.js", "../../../../node_modules/exenv/index.js", "../../../../node_modules/react-modal/lib/helpers/safeHTMLElement.js", "../../../../node_modules/react-modal/lib/helpers/ariaAppHider.js", "../../../../node_modules/react-modal/lib/helpers/classList.js", "../../../../node_modules/react-modal/lib/helpers/portalOpenInstances.js", "../../../../node_modules/react-modal/lib/helpers/bodyTrap.js", "../../../../node_modules/react-modal/lib/components/ModalPortal.js", "../../../../node_modules/react-lifecycles-compat/react-lifecycles-compat.cjs.js", "../../../../node_modules/react-modal/lib/components/Modal.js", "../../../../node_modules/react-modal/lib/index.js", "../../../../bundles/apps/webcast/src/hooks/useViewerSignupReminderToggle.ts", "../../../../node_modules/@babel/runtime/helpers/esm/typeof.js", "../../../../node_modules/@babel/runtime/helpers/esm/toPrimitive.js", "../../../../node_modules/@babel/runtime/helpers/esm/toPropertyKey.js", "../../../../node_modules/@babel/runtime/helpers/esm/defineProperty.js", "../../../../node_modules/@babel/runtime/helpers/esm/classCallCheck.js", "../../../../node_modules/@babel/runtime/helpers/esm/createClass.js", "../../../../node_modules/react-i18next/dist/es/unescape.js", "../../../../node_modules/react-i18next/dist/es/context.js", "../../../../node_modules/react-i18next/dist/es/utils.js", "../../../../node_modules/@babel/runtime/helpers/esm/arrayWithHoles.js", "../../../../node_modules/@babel/runtime/helpers/esm/iterableToArrayLimit.js", "../../../../node_modules/@babel/runtime/helpers/esm/arrayLikeToArray.js", "../../../../node_modules/@babel/runtime/helpers/esm/unsupportedIterableToArray.js", "../../../../node_modules/@babel/runtime/helpers/esm/nonIterableRest.js", "../../../../node_modules/@babel/runtime/helpers/esm/slicedToArray.js", "../../../../node_modules/react-i18next/dist/es/useTranslation.js", "../../../../node_modules/react-i18next/dist/es/index.js", "../../../../node_modules/lodash.debounce/index.js", "../../../../bundles/apps/webcast/src/components/bidder/BidderLanguageSelectorCmp.tsx", "../../../../bundles/apps/webcast/src/components/bidder/BidderPageHeaderCmp.tsx", "../../../../bundles/apps/webcast/src/components/CurrencyAmountDisplay.tsx", "../../../../node_modules/fast-deep-equal/index.js", "../../../../node_modules/sister/src/sister.js", "../../../../node_modules/load-script/index.js", "../../../../node_modules/youtube-player/dist/loadYouTubeIframeApi.js", "../../../../node_modules/ms/index.js", "../../../../node_modules/debug/src/debug.js", "../../../../node_modules/debug/src/browser.js", "../../../../node_modules/youtube-player/dist/functionNames.js", "../../../../node_modules/youtube-player/dist/eventNames.js", "../../../../node_modules/youtube-player/dist/constants/PlayerStates.js", "../../../../node_modules/youtube-player/dist/FunctionStateMap.js", "../../../../node_modules/youtube-player/dist/YouTubePlayer.js", "../../../../node_modules/youtube-player/dist/index.js", "../../../../node_modules/react-youtube/src/YouTube.tsx", "../../../../bundles/apps/webcast/src/components/bidder/BidderLotDetailsCmp.tsx", "../../../../node_modules/intersection-observer/intersection-observer.js", "../../../../node_modules/@react-hook/passive-layout-effect/dist/module/index.js", "../../../../node_modules/@react-hook/intersection-observer/dist/module/index.js", "../../../../bundles/apps/webcast/src/components/bidder/BidderCatalogLotsListCmp.tsx", "../../../../bundles/apps/webcast/src/components/bidder/BidderMyPurchasesCmp.tsx", "../../../../bundles/apps/webcast/src/components/bidder/BidderCatalogAndMyPurchasesCmp.tsx", "../../../../node_modules/moment/moment.js", "../../../../bundles/apps/webcast/src/components/bidder/BidderChatBoxCmp.tsx", "../../../../bundles/apps/webcast/src/components/bidder/BidderRoundStopInfoCmp.tsx", "../../../../bundles/apps/webcast/src/components/bidder/BidderBidHistoryCmp.tsx", "../../../../bundles/core/src/hooks/useIsMobileDevice.ts", "../../../../node_modules/@use-gesture/core/dist/maths-0ab39ae9.esm.js", "../../../../node_modules/@use-gesture/core/dist/actions-fe213e88.esm.js", "../../../../node_modules/@use-gesture/core/actions/dist/use-gesture-core-actions.esm.js", "../../../../node_modules/@use-gesture/core/dist/use-gesture-core.esm.js", "../../../../node_modules/@use-gesture/core/utils/dist/use-gesture-core-utils.esm.js", "../../../../node_modules/@use-gesture/core/types/dist/use-gesture-core-types.esm.js", "../../../../node_modules/@use-gesture/react/dist/use-gesture-react.esm.js", "../../../../node_modules/@react-spring/rafz/src/index.ts", "../../../../node_modules/@react-spring/shared/src/globals.ts", "../../../../node_modules/@react-spring/shared/src/helpers.ts", "../../../../node_modules/@react-spring/shared/src/FrameLoop.ts", "../../../../node_modules/@react-spring/shared/src/clamp.ts", "../../../../node_modules/@react-spring/shared/src/colors.ts", "../../../../node_modules/@react-spring/shared/src/colorMatchers.ts", "../../../../node_modules/@react-spring/shared/src/normalizeColor.ts", "../../../../node_modules/@react-spring/shared/src/colorToRgba.ts", "../../../../node_modules/@react-spring/shared/src/createInterpolator.ts", "../../../../node_modules/@react-spring/shared/src/easings.ts", "../../../../node_modules/@react-spring/shared/src/fluids.ts", "../../../../node_modules/@react-spring/shared/src/regexs.ts", "../../../../node_modules/@react-spring/shared/src/variableToRgba.ts", "../../../../node_modules/@react-spring/shared/src/stringInterpolation.ts", "../../../../node_modules/@react-spring/shared/src/deprecations.ts", "../../../../node_modules/@react-spring/shared/src/isAnimatedString.ts", "../../../../node_modules/@react-spring/shared/src/dom-events/scroll/index.ts", "../../../../node_modules/@react-spring/shared/src/dom-events/resize/resizeElement.ts", "../../../../node_modules/@react-spring/shared/src/dom-events/resize/resizeWindow.ts", "../../../../node_modules/@react-spring/shared/src/dom-events/resize/index.ts", "../../../../node_modules/@react-spring/shared/src/progress.ts", "../../../../node_modules/@react-spring/shared/src/dom-events/scroll/ScrollHandler.ts", "../../../../node_modules/@react-spring/shared/src/hooks/useConstant.ts", "../../../../node_modules/@react-spring/shared/src/hooks/useForceUpdate.ts", "../../../../node_modules/@react-spring/shared/src/hooks/useIsMounted.ts", "../../../../node_modules/@react-spring/shared/src/hooks/useIsomorphicLayoutEffect.ts", "../../../../node_modules/@react-spring/shared/src/hooks/useMemoOne.ts", "../../../../node_modules/@react-spring/shared/src/hooks/useOnce.ts", "../../../../node_modules/@react-spring/shared/src/hooks/usePrev.ts", "../../../../node_modules/@react-spring/shared/src/hooks/useReducedMotion.ts", "../../../../node_modules/@react-spring/shared/src/index.ts", "../../../../node_modules/@react-spring/animated/src/Animated.ts", "../../../../node_modules/@react-spring/animated/src/AnimatedValue.ts", "../../../../node_modules/@react-spring/animated/src/AnimatedString.ts", "../../../../node_modules/@react-spring/animated/src/AnimatedArray.ts", "../../../../node_modules/@react-spring/animated/src/AnimatedObject.ts", "../../../../node_modules/@react-spring/animated/src/context.ts", "../../../../node_modules/@react-spring/animated/src/getAnimatedType.ts", "../../../../node_modules/@react-spring/animated/src/createHost.ts", "../../../../node_modules/@react-spring/animated/src/withAnimated.tsx", "../../../../node_modules/@react-spring/core/src/hooks/useChain.ts", "../../../../node_modules/@react-spring/core/src/helpers.ts", "../../../../node_modules/@react-spring/core/src/hooks/useSpring.ts", "../../../../node_modules/@react-spring/core/src/hooks/useSprings.ts", "../../../../node_modules/@react-spring/core/src/SpringValue.ts", "../../../../node_modules/@react-spring/core/src/AnimationConfig.ts", "../../../../node_modules/@react-spring/core/src/constants.ts", "../../../../node_modules/@react-spring/core/src/Animation.ts", "../../../../node_modules/@react-spring/core/src/scheduleProps.ts", "../../../../node_modules/@react-spring/core/src/runAsync.ts", "../../../../node_modules/@react-spring/core/src/AnimationResult.ts", "../../../../node_modules/@react-spring/core/src/FrameValue.ts", "../../../../node_modules/@react-spring/core/src/SpringPhase.ts", "../../../../node_modules/@react-spring/core/src/Controller.ts", "../../../../node_modules/@react-spring/core/src/SpringContext.tsx", "../../../../node_modules/@react-spring/core/src/SpringRef.ts", "../../../../node_modules/@react-spring/core/src/hooks/useSpringRef.ts", "../../../../node_modules/@react-spring/core/src/hooks/useSpringValue.ts", "../../../../node_modules/@react-spring/core/src/hooks/useTrail.ts", "../../../../node_modules/@react-spring/core/src/hooks/useTransition.tsx", "../../../../node_modules/@react-spring/core/src/hooks/useScroll.ts", "../../../../node_modules/@react-spring/core/src/hooks/useResize.ts", "../../../../node_modules/@react-spring/core/src/hooks/useInView.ts", "../../../../node_modules/@react-spring/core/src/components/Spring.tsx", "../../../../node_modules/@react-spring/core/src/components/Trail.tsx", "../../../../node_modules/@react-spring/core/src/components/Transition.tsx", "../../../../node_modules/@react-spring/core/src/interpolate.ts", "../../../../node_modules/@react-spring/core/src/Interpolation.ts", "../../../../node_modules/@react-spring/core/src/globals.ts", "../../../../node_modules/@react-spring/core/src/index.ts", "../../../../node_modules/@react-spring/web/src/index.ts", "../../../../node_modules/@react-spring/web/src/applyAnimatedValues.ts", "../../../../node_modules/@react-spring/web/src/AnimatedStyle.ts", "../../../../node_modules/@react-spring/web/src/primitives.ts", "../../../../bundles/apps/webcast/src/components/bidder/SwipeButtonAnimatedCmp.tsx", "../../../../bundles/apps/webcast/src/components/bidder/BidderRoundBiddingCmp.tsx", "../../../../bundles/apps/webcast/src/components/bidder/BidderRoundChoiceLotsSelectCmp.tsx", "../../../../bundles/apps/webcast/src/components/bidder/BidderBiddingAreaLayoutRootCmp.tsx", "../../../../bundles/apps/webcast/src/components/bidder/BidderCurrentRoundLotsCmp.tsx", "../../../../bundles/apps/webcast/src/components/bidder/BidderMediaStreamingRootCmp.tsx", "../../../../bundles/apps/webcast/src/components/bidder/BidderRootCmp.tsx", "../../../../node_modules/@babel/runtime/helpers/esm/inherits.js", "../../../../node_modules/@babel/runtime/helpers/esm/possibleConstructorReturn.js", "../../../../node_modules/@babel/runtime/helpers/esm/getPrototypeOf.js", "../../../../node_modules/@babel/runtime/helpers/esm/iterableToArray.js", "../../../../node_modules/@babel/runtime/helpers/esm/toArray.js", "../../../../node_modules/i18next/dist/esm/i18next.js", "../../../../bundles/apps/webcast/src/translations/en.json", "../../../../bundles/apps/webcast/src/translations/es.json", "../../../../bundles/apps/webcast/src/translations/de.json", "../../../../bundles/apps/webcast/src/translations/nl.json", "../../../../bundles/apps/webcast/src/translations/pt.json", "../../../../bundles/apps/webcast/src/translations/fr.json", "../../../../bundles/apps/webcast/src/i18n.ts", "../../../../bundles/apps/webcast/src/screen_bidder.tsx", "../../../../bundles/apps/webcast/src/components/onsite/OnsiteInfoHeaderCmp.tsx", "../../../../bundles/apps/webcast/src/components/onsite/OnsiteRootCmp.tsx", "../../../../bundles/apps/webcast/src/screen_onsite.tsx", "../../../../bundles/apps/webcast/src/hooks/useWindowResize.ts", "../../../../bundles/apps/webcast/src/components/auctioneer/AuctioneerRootCmp.tsx", "../../../../bundles/apps/webcast/src/screen_auctioneer.tsx", "../../../../bundles/apps/webcast/src/components/viewer_embedded/ViewerEmbeddedHeaderCmp.tsx", "../../../../bundles/apps/webcast/src/components/viewer_embedded/ViewerEmbeddedMediaStreamingRootCmp.tsx", "../../../../bundles/apps/webcast/src/components/viewer_embedded/ViewerEmbeddedLotDetailsCmp.tsx", "../../../../bundles/apps/webcast/src/components/viewer_embedded/ViewerEmbeddedCurrentRoundLotsCmp.tsx", "../../../../bundles/apps/webcast/src/components/viewer_embedded/ViewerEmbeddedRootCmp.tsx", "../../../../bundles/apps/webcast/src/screen_viewer_embedded.tsx", "../../../../bundles/apps/webcast/src/index.ts"], "sourcesContent": ["const errors = {\n\t0: \"Illegal state\",\n\t1: \"Immer drafts cannot have computed properties\",\n\t2: \"This object has been frozen and should not be mutated\",\n\t3(data: any) {\n\t\treturn (\n\t\t\t\"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? \" +\n\t\t\tdata\n\t\t)\n\t},\n\t4: \"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.\",\n\t5: \"Immer forbids circular references\",\n\t6: \"The first or second argument to `produce` must be a function\",\n\t7: \"The third argument to `produce` must be a function or undefined\",\n\t8: \"First argument to `createDraft` must be a plain object, an array, or an immerable object\",\n\t9: \"First argument to `finishDraft` must be a draft returned by `createDraft`\",\n\t10: \"The given draft is already finalized\",\n\t11: \"Object.defineProperty() cannot be used on an Immer draft\",\n\t12: \"Object.setPrototypeOf() cannot be used on an Immer draft\",\n\t13: \"Immer only supports deleting array indices\",\n\t14: \"Immer only supports setting array indices and the 'length' property\",\n\t15(path: string) {\n\t\treturn \"Cannot apply patch, path doesn't resolve: \" + path\n\t},\n\t16: 'Sets cannot have \"replace\" patches.',\n\t17(op: string) {\n\t\treturn \"Unsupported patch operation: \" + op\n\t},\n\t18(plugin: string) {\n\t\treturn `The plugin for '${plugin}' has not been loaded into Immer. To enable the plugin, import and call \\`enable${plugin}()\\` when initializing your application.`\n\t},\n\t20: \"Cannot use proxies if Proxy, Proxy.revocable or Reflect are not available\",\n\t21(thing: string) {\n\t\treturn `produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${thing}'`\n\t},\n\t22(thing: string) {\n\t\treturn `'current' expects a draft, got: ${thing}`\n\t},\n\t23(thing: string) {\n\t\treturn `'original' expects a draft, got: ${thing}`\n\t},\n\t24: \"Patching reserved attributes like __proto__, prototype and constructor is not allowed\"\n} as const\n\nexport function die(error: keyof typeof errors, ...args: any[]): never {\n\tif (__DEV__) {\n\t\tconst e = errors[error]\n\t\tconst msg = !e\n\t\t\t? \"unknown error nr: \" + error\n\t\t\t: typeof e === \"function\"\n\t\t\t? e.apply(null, args as any)\n\t\t\t: e\n\t\tthrow new Error(`[Immer] ${msg}`)\n\t}\n\tthrow new Error(\n\t\t`[Immer] minified error nr: ${error}${\n\t\t\targs.length ? \" \" + args.map(s => `'${s}'`).join(\",\") : \"\"\n\t\t}. Find the full error at: https://bit.ly/3cXEKWf`\n\t)\n}\n", "import {\n\tDRAFT_STATE,\n\tDRAFTABLE,\n\thasSet,\n\tObjectish,\n\tDrafted,\n\tAnyObject,\n\tAnyMap,\n\tAnySet,\n\tImmerState,\n\thasMap,\n\tArchtype,\n\tdie\n} from \"../internal\"\n\n/** Returns true if the given value is an Immer draft */\n/*#__PURE__*/\nexport function isDraft(value: any): boolean {\n\treturn !!value && !!value[DRAFT_STATE]\n}\n\n/** Returns true if the given value can be drafted by Immer */\n/*#__PURE__*/\nexport function isDraftable(value: any): boolean {\n\tif (!value) return false\n\treturn (\n\t\tisPlainObject(value) ||\n\t\tArray.isArray(value) ||\n\t\t!!value[DRAFTABLE] ||\n\t\t!!value.constructor?.[DRAFTABLE] ||\n\t\tisMap(value) ||\n\t\tisSet(value)\n\t)\n}\n\nconst objectCtorString = Object.prototype.constructor.toString()\n/*#__PURE__*/\nexport function isPlainObject(value: any): boolean {\n\tif (!value || typeof value !== \"object\") return false\n\tconst proto = Object.getPrototypeOf(value)\n\tif (proto === null) {\n\t\treturn true\n\t}\n\tconst Ctor =\n\t\tObject.hasOwnProperty.call(proto, \"constructor\") && proto.constructor\n\n\tif (Ctor === Object) return true\n\n\treturn (\n\t\ttypeof Ctor == \"function\" &&\n\t\tFunction.toString.call(Ctor) === objectCtorString\n\t)\n}\n\n/** Get the underlying object that is represented by the given draft */\n/*#__PURE__*/\nexport function original(value: T): T | undefined\nexport function original(value: Drafted): any {\n\tif (!isDraft(value)) die(23, value)\n\treturn value[DRAFT_STATE].base_\n}\n\n/*#__PURE__*/\nexport const ownKeys: (target: AnyObject) => PropertyKey[] =\n\ttypeof Reflect !== \"undefined\" && Reflect.ownKeys\n\t\t? Reflect.ownKeys\n\t\t: typeof Object.getOwnPropertySymbols !== \"undefined\"\n\t\t? obj =>\n\t\t\t\tObject.getOwnPropertyNames(obj).concat(\n\t\t\t\t\tObject.getOwnPropertySymbols(obj) as any\n\t\t\t\t)\n\t\t: /* istanbul ignore next */ Object.getOwnPropertyNames\n\nexport const getOwnPropertyDescriptors =\n\tObject.getOwnPropertyDescriptors ||\n\tfunction getOwnPropertyDescriptors(target: any) {\n\t\t// Polyfill needed for Hermes and IE, see https://github.com/facebook/hermes/issues/274\n\t\tconst res: any = {}\n\t\townKeys(target).forEach(key => {\n\t\t\tres[key] = Object.getOwnPropertyDescriptor(target, key)\n\t\t})\n\t\treturn res\n\t}\n\nexport function each(\n\tobj: T,\n\titer: (key: string | number, value: any, source: T) => void,\n\tenumerableOnly?: boolean\n): void\nexport function each(obj: any, iter: any, enumerableOnly = false) {\n\tif (getArchtype(obj) === Archtype.Object) {\n\t\t;(enumerableOnly ? Object.keys : ownKeys)(obj).forEach(key => {\n\t\t\tif (!enumerableOnly || typeof key !== \"symbol\") iter(key, obj[key], obj)\n\t\t})\n\t} else {\n\t\tobj.forEach((entry: any, index: any) => iter(index, entry, obj))\n\t}\n}\n\n/*#__PURE__*/\nexport function getArchtype(thing: any): Archtype {\n\t/* istanbul ignore next */\n\tconst state: undefined | ImmerState = thing[DRAFT_STATE]\n\treturn state\n\t\t? state.type_ > 3\n\t\t\t? state.type_ - 4 // cause Object and Array map back from 4 and 5\n\t\t\t: (state.type_ as any) // others are the same\n\t\t: Array.isArray(thing)\n\t\t? Archtype.Array\n\t\t: isMap(thing)\n\t\t? Archtype.Map\n\t\t: isSet(thing)\n\t\t? Archtype.Set\n\t\t: Archtype.Object\n}\n\n/*#__PURE__*/\nexport function has(thing: any, prop: PropertyKey): boolean {\n\treturn getArchtype(thing) === Archtype.Map\n\t\t? thing.has(prop)\n\t\t: Object.prototype.hasOwnProperty.call(thing, prop)\n}\n\n/*#__PURE__*/\nexport function get(thing: AnyMap | AnyObject, prop: PropertyKey): any {\n\t// @ts-ignore\n\treturn getArchtype(thing) === Archtype.Map ? thing.get(prop) : thing[prop]\n}\n\n/*#__PURE__*/\nexport function set(thing: any, propOrOldValue: PropertyKey, value: any) {\n\tconst t = getArchtype(thing)\n\tif (t === Archtype.Map) thing.set(propOrOldValue, value)\n\telse if (t === Archtype.Set) {\n\t\tthing.add(value)\n\t} else thing[propOrOldValue] = value\n}\n\n/*#__PURE__*/\nexport function is(x: any, y: any): boolean {\n\t// From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js\n\tif (x === y) {\n\t\treturn x !== 0 || 1 / x === 1 / y\n\t} else {\n\t\treturn x !== x && y !== y\n\t}\n}\n\n/*#__PURE__*/\nexport function isMap(target: any): target is AnyMap {\n\treturn hasMap && target instanceof Map\n}\n\n/*#__PURE__*/\nexport function isSet(target: any): target is AnySet {\n\treturn hasSet && target instanceof Set\n}\n/*#__PURE__*/\nexport function latest(state: ImmerState): any {\n\treturn state.copy_ || state.base_\n}\n\n/*#__PURE__*/\nexport function shallowCopy(base: any) {\n\tif (Array.isArray(base)) return Array.prototype.slice.call(base)\n\tconst descriptors = getOwnPropertyDescriptors(base)\n\tdelete descriptors[DRAFT_STATE as any]\n\tlet keys = ownKeys(descriptors)\n\tfor (let i = 0; i < keys.length; i++) {\n\t\tconst key: any = keys[i]\n\t\tconst desc = descriptors[key]\n\t\tif (desc.writable === false) {\n\t\t\tdesc.writable = true\n\t\t\tdesc.configurable = true\n\t\t}\n\t\t// like object.assign, we will read any _own_, get/set accessors. This helps in dealing\n\t\t// with libraries that trap values, like mobx or vue\n\t\t// unlike object.assign, non-enumerables will be copied as well\n\t\tif (desc.get || desc.set)\n\t\t\tdescriptors[key] = {\n\t\t\t\tconfigurable: true,\n\t\t\t\twritable: true, // could live with !!desc.set as well here...\n\t\t\t\tenumerable: desc.enumerable,\n\t\t\t\tvalue: base[key]\n\t\t\t}\n\t}\n\treturn Object.create(Object.getPrototypeOf(base), descriptors)\n}\n\n/**\n * Freezes draftable objects. Returns the original object.\n * By default freezes shallowly, but if the second argument is `true` it will freeze recursively.\n *\n * @param obj\n * @param deep\n */\nexport function freeze(obj: T, deep?: boolean): T\nexport function freeze(obj: any, deep: boolean = false): T {\n\tif (isFrozen(obj) || isDraft(obj) || !isDraftable(obj)) return obj\n\tif (getArchtype(obj) > 1 /* Map or Set */) {\n\t\tobj.set = obj.add = obj.clear = obj.delete = dontMutateFrozenCollections as any\n\t}\n\tObject.freeze(obj)\n\tif (deep) each(obj, (key, value) => freeze(value, true), true)\n\treturn obj\n}\n\nfunction dontMutateFrozenCollections() {\n\tdie(2)\n}\n\nexport function isFrozen(obj: any): boolean {\n\tif (obj == null || typeof obj !== \"object\") return true\n\t// See #600, IE dies on non-objects in Object.isFrozen\n\treturn Object.isFrozen(obj)\n}\n", "import {\n\tImmerState,\n\tPatch,\n\tImmerScope,\n\tDrafted,\n\tAnyObject,\n\tImmerBaseState,\n\tAnyMap,\n\tAnySet,\n\tProxyType,\n\tdie\n} from \"../internal\"\n\n/** Plugin utilities */\nconst plugins: {\n\tPatches?: {\n\t\tgeneratePatches_(\n\t\t\tstate: ImmerState,\n\t\t\tbasePath: PatchPath,\n\t\t\tpatches: Patch[],\n\t\t\tinversePatches: Patch[]\n\t\t): void\n\t\tgenerateReplacementPatches_(\n\t\t\tbase: any,\n\t\t\treplacement: any,\n\t\t\tpatches: Patch[],\n\t\t\tinversePatches: Patch[]\n\t\t): void\n\t\tapplyPatches_(draft: T, patches: Patch[]): T\n\t}\n\tES5?: {\n\t\twillFinalizeES5_(scope: ImmerScope, result: any, isReplaced: boolean): void\n\t\tcreateES5Proxy_(\n\t\t\tbase: T,\n\t\t\tparent?: ImmerState\n\t\t): Drafted\n\t\thasChanges_(state: ES5ArrayState | ES5ObjectState): boolean\n\t}\n\tMapSet?: {\n\t\tproxyMap_(target: T, parent?: ImmerState): T\n\t\tproxySet_(target: T, parent?: ImmerState): T\n\t}\n} = {}\n\ntype Plugins = typeof plugins\n\nexport function getPlugin(\n\tpluginKey: K\n): Exclude {\n\tconst plugin = plugins[pluginKey]\n\tif (!plugin) {\n\t\tdie(18, pluginKey)\n\t}\n\t// @ts-ignore\n\treturn plugin\n}\n\nexport function loadPlugin(\n\tpluginKey: K,\n\timplementation: Plugins[K]\n): void {\n\tif (!plugins[pluginKey]) plugins[pluginKey] = implementation\n}\n\n/** ES5 Plugin */\n\ninterface ES5BaseState extends ImmerBaseState {\n\tassigned_: {[key: string]: any}\n\tparent_?: ImmerState\n\trevoked_: boolean\n}\n\nexport interface ES5ObjectState extends ES5BaseState {\n\ttype_: ProxyType.ES5Object\n\tdraft_: Drafted\n\tbase_: AnyObject\n\tcopy_: AnyObject | null\n}\n\nexport interface ES5ArrayState extends ES5BaseState {\n\ttype_: ProxyType.ES5Array\n\tdraft_: Drafted\n\tbase_: any\n\tcopy_: any\n}\n\n/** Map / Set plugin */\n\nexport interface MapState extends ImmerBaseState {\n\ttype_: ProxyType.Map\n\tcopy_: AnyMap | undefined\n\tassigned_: Map | undefined\n\tbase_: AnyMap\n\trevoked_: boolean\n\tdraft_: Drafted\n}\n\nexport interface SetState extends ImmerBaseState {\n\ttype_: ProxyType.Set\n\tcopy_: AnySet | undefined\n\tbase_: AnySet\n\tdrafts_: Map // maps the original value to the draft value in the new set\n\trevoked_: boolean\n\tdraft_: Drafted\n}\n\n/** Patches plugin */\n\nexport type PatchPath = (string | number)[]\n", "import {\n\tPatch,\n\tPatchListener,\n\tDrafted,\n\tImmer,\n\tDRAFT_STATE,\n\tImmerState,\n\tProxyType,\n\tgetPlugin\n} from \"../internal\"\nimport {die} from \"../utils/errors\"\n\n/** Each scope represents a `produce` call. */\n\nexport interface ImmerScope {\n\tpatches_?: Patch[]\n\tinversePatches_?: Patch[]\n\tcanAutoFreeze_: boolean\n\tdrafts_: any[]\n\tparent_?: ImmerScope\n\tpatchListener_?: PatchListener\n\timmer_: Immer\n\tunfinalizedDrafts_: number\n}\n\nlet currentScope: ImmerScope | undefined\n\nexport function getCurrentScope() {\n\tif (__DEV__ && !currentScope) die(0)\n\treturn currentScope!\n}\n\nfunction createScope(\n\tparent_: ImmerScope | undefined,\n\timmer_: Immer\n): ImmerScope {\n\treturn {\n\t\tdrafts_: [],\n\t\tparent_,\n\t\timmer_,\n\t\t// Whenever the modified draft contains a draft from another scope, we\n\t\t// need to prevent auto-freezing so the unowned draft can be finalized.\n\t\tcanAutoFreeze_: true,\n\t\tunfinalizedDrafts_: 0\n\t}\n}\n\nexport function usePatchesInScope(\n\tscope: ImmerScope,\n\tpatchListener?: PatchListener\n) {\n\tif (patchListener) {\n\t\tgetPlugin(\"Patches\") // assert we have the plugin\n\t\tscope.patches_ = []\n\t\tscope.inversePatches_ = []\n\t\tscope.patchListener_ = patchListener\n\t}\n}\n\nexport function revokeScope(scope: ImmerScope) {\n\tleaveScope(scope)\n\tscope.drafts_.forEach(revokeDraft)\n\t// @ts-ignore\n\tscope.drafts_ = null\n}\n\nexport function leaveScope(scope: ImmerScope) {\n\tif (scope === currentScope) {\n\t\tcurrentScope = scope.parent_\n\t}\n}\n\nexport function enterScope(immer: Immer) {\n\treturn (currentScope = createScope(currentScope, immer))\n}\n\nfunction revokeDraft(draft: Drafted) {\n\tconst state: ImmerState = draft[DRAFT_STATE]\n\tif (\n\t\tstate.type_ === ProxyType.ProxyObject ||\n\t\tstate.type_ === ProxyType.ProxyArray\n\t)\n\t\tstate.revoke_()\n\telse state.revoked_ = true\n}\n", "import {\n\tImmerScope,\n\tDRAFT_STATE,\n\tisDraftable,\n\tNOTHING,\n\tPatchPath,\n\teach,\n\thas,\n\tfreeze,\n\tImmerState,\n\tisDraft,\n\tSetState,\n\tset,\n\tProxyType,\n\tgetPlugin,\n\tdie,\n\trevokeScope,\n\tisFrozen,\n\tshallowCopy\n} from \"../internal\"\n\nexport function processResult(result: any, scope: ImmerScope) {\n\tscope.unfinalizedDrafts_ = scope.drafts_.length\n\tconst baseDraft = scope.drafts_![0]\n\tconst isReplaced = result !== undefined && result !== baseDraft\n\tif (!scope.immer_.useProxies_)\n\t\tgetPlugin(\"ES5\").willFinalizeES5_(scope, result, isReplaced)\n\tif (isReplaced) {\n\t\tif (baseDraft[DRAFT_STATE].modified_) {\n\t\t\trevokeScope(scope)\n\t\t\tdie(4)\n\t\t}\n\t\tif (isDraftable(result)) {\n\t\t\t// Finalize the result in case it contains (or is) a subset of the draft.\n\t\t\tresult = finalize(scope, result)\n\t\t\tif (!scope.parent_) maybeFreeze(scope, result)\n\t\t}\n\t\tif (scope.patches_) {\n\t\t\tgetPlugin(\"Patches\").generateReplacementPatches_(\n\t\t\t\tbaseDraft[DRAFT_STATE].base_,\n\t\t\t\tresult,\n\t\t\t\tscope.patches_,\n\t\t\t\tscope.inversePatches_!\n\t\t\t)\n\t\t}\n\t} else {\n\t\t// Finalize the base draft.\n\t\tresult = finalize(scope, baseDraft, [])\n\t}\n\trevokeScope(scope)\n\tif (scope.patches_) {\n\t\tscope.patchListener_!(scope.patches_, scope.inversePatches_!)\n\t}\n\treturn result !== NOTHING ? result : undefined\n}\n\nfunction finalize(rootScope: ImmerScope, value: any, path?: PatchPath) {\n\t// Don't recurse in tho recursive data structures\n\tif (isFrozen(value)) return value\n\n\tconst state: ImmerState = value[DRAFT_STATE]\n\t// A plain object, might need freezing, might contain drafts\n\tif (!state) {\n\t\teach(\n\t\t\tvalue,\n\t\t\t(key, childValue) =>\n\t\t\t\tfinalizeProperty(rootScope, state, value, key, childValue, path),\n\t\t\ttrue // See #590, don't recurse into non-enumerable of non drafted objects\n\t\t)\n\t\treturn value\n\t}\n\t// Never finalize drafts owned by another scope.\n\tif (state.scope_ !== rootScope) return value\n\t// Unmodified draft, return the (frozen) original\n\tif (!state.modified_) {\n\t\tmaybeFreeze(rootScope, state.base_, true)\n\t\treturn state.base_\n\t}\n\t// Not finalized yet, let's do that now\n\tif (!state.finalized_) {\n\t\tstate.finalized_ = true\n\t\tstate.scope_.unfinalizedDrafts_--\n\t\tconst result =\n\t\t\t// For ES5, create a good copy from the draft first, with added keys and without deleted keys.\n\t\t\tstate.type_ === ProxyType.ES5Object || state.type_ === ProxyType.ES5Array\n\t\t\t\t? (state.copy_ = shallowCopy(state.draft_))\n\t\t\t\t: state.copy_\n\t\t// Finalize all children of the copy\n\t\t// For sets we clone before iterating, otherwise we can get in endless loop due to modifying during iteration, see #628\n\t\t// To preserve insertion order in all cases we then clear the set\n\t\t// And we let finalizeProperty know it needs to re-add non-draft children back to the target\n\t\tlet resultEach = result\n\t\tlet isSet = false\n\t\tif (state.type_ === ProxyType.Set) {\n\t\t\tresultEach = new Set(result)\n\t\t\tresult.clear()\n\t\t\tisSet = true\n\t\t}\n\t\teach(resultEach, (key, childValue) =>\n\t\t\tfinalizeProperty(rootScope, state, result, key, childValue, path, isSet)\n\t\t)\n\t\t// everything inside is frozen, we can freeze here\n\t\tmaybeFreeze(rootScope, result, false)\n\t\t// first time finalizing, let's create those patches\n\t\tif (path && rootScope.patches_) {\n\t\t\tgetPlugin(\"Patches\").generatePatches_(\n\t\t\t\tstate,\n\t\t\t\tpath,\n\t\t\t\trootScope.patches_,\n\t\t\t\trootScope.inversePatches_!\n\t\t\t)\n\t\t}\n\t}\n\treturn state.copy_\n}\n\nfunction finalizeProperty(\n\trootScope: ImmerScope,\n\tparentState: undefined | ImmerState,\n\ttargetObject: any,\n\tprop: string | number,\n\tchildValue: any,\n\trootPath?: PatchPath,\n\ttargetIsSet?: boolean\n) {\n\tif (__DEV__ && childValue === targetObject) die(5)\n\tif (isDraft(childValue)) {\n\t\tconst path =\n\t\t\trootPath &&\n\t\t\tparentState &&\n\t\t\tparentState!.type_ !== ProxyType.Set && // Set objects are atomic since they have no keys.\n\t\t\t!has((parentState as Exclude).assigned_!, prop) // Skip deep patches for assigned keys.\n\t\t\t\t? rootPath!.concat(prop)\n\t\t\t\t: undefined\n\t\t// Drafts owned by `scope` are finalized here.\n\t\tconst res = finalize(rootScope, childValue, path)\n\t\tset(targetObject, prop, res)\n\t\t// Drafts from another scope must prevented to be frozen\n\t\t// if we got a draft back from finalize, we're in a nested produce and shouldn't freeze\n\t\tif (isDraft(res)) {\n\t\t\trootScope.canAutoFreeze_ = false\n\t\t} else return\n\t} else if (targetIsSet) {\n\t\ttargetObject.add(childValue)\n\t}\n\t// Search new objects for unfinalized drafts. Frozen objects should never contain drafts.\n\tif (isDraftable(childValue) && !isFrozen(childValue)) {\n\t\tif (!rootScope.immer_.autoFreeze_ && rootScope.unfinalizedDrafts_ < 1) {\n\t\t\t// optimization: if an object is not a draft, and we don't have to\n\t\t\t// deepfreeze everything, and we are sure that no drafts are left in the remaining object\n\t\t\t// cause we saw and finalized all drafts already; we can stop visiting the rest of the tree.\n\t\t\t// This benefits especially adding large data tree's without further processing.\n\t\t\t// See add-data.js perf test\n\t\t\treturn\n\t\t}\n\t\tfinalize(rootScope, childValue)\n\t\t// immer deep freezes plain objects, so if there is no parent state, we freeze as well\n\t\tif (!parentState || !parentState.scope_.parent_)\n\t\t\tmaybeFreeze(rootScope, childValue)\n\t}\n}\n\nfunction maybeFreeze(scope: ImmerScope, value: any, deep = false) {\n\t// we never freeze for a non-root scope; as it would prevent pruning for drafts inside wrapping objects\n\tif (!scope.parent_ && scope.immer_.autoFreeze_ && scope.canAutoFreeze_) {\n\t\tfreeze(value, deep)\n\t}\n}\n", "import {\n\teach,\n\thas,\n\tis,\n\tisDraftable,\n\tshallowCopy,\n\tlatest,\n\tImmerBaseState,\n\tImmerState,\n\tDrafted,\n\tAnyObject,\n\tAnyArray,\n\tObjectish,\n\tgetCurrentScope,\n\tDRAFT_STATE,\n\tdie,\n\tcreateProxy,\n\tProxyType\n} from \"../internal\"\n\ninterface ProxyBaseState extends ImmerBaseState {\n\tassigned_: {\n\t\t[property: string]: boolean\n\t}\n\tparent_?: ImmerState\n\trevoke_(): void\n}\n\nexport interface ProxyObjectState extends ProxyBaseState {\n\ttype_: ProxyType.ProxyObject\n\tbase_: any\n\tcopy_: any\n\tdraft_: Drafted\n}\n\nexport interface ProxyArrayState extends ProxyBaseState {\n\ttype_: ProxyType.ProxyArray\n\tbase_: AnyArray\n\tcopy_: AnyArray | null\n\tdraft_: Drafted\n}\n\ntype ProxyState = ProxyObjectState | ProxyArrayState\n\n/**\n * Returns a new draft of the `base` object.\n *\n * The second argument is the parent draft-state (used internally).\n */\nexport function createProxyProxy(\n\tbase: T,\n\tparent?: ImmerState\n): Drafted {\n\tconst isArray = Array.isArray(base)\n\tconst state: ProxyState = {\n\t\ttype_: isArray ? ProxyType.ProxyArray : (ProxyType.ProxyObject as any),\n\t\t// Track which produce call this is associated with.\n\t\tscope_: parent ? parent.scope_ : getCurrentScope()!,\n\t\t// True for both shallow and deep changes.\n\t\tmodified_: false,\n\t\t// Used during finalization.\n\t\tfinalized_: false,\n\t\t// Track which properties have been assigned (true) or deleted (false).\n\t\tassigned_: {},\n\t\t// The parent draft state.\n\t\tparent_: parent,\n\t\t// The base state.\n\t\tbase_: base,\n\t\t// The base proxy.\n\t\tdraft_: null as any, // set below\n\t\t// The base copy with any updated values.\n\t\tcopy_: null,\n\t\t// Called by the `produce` function.\n\t\trevoke_: null as any,\n\t\tisManual_: false\n\t}\n\n\t// the traps must target something, a bit like the 'real' base.\n\t// but also, we need to be able to determine from the target what the relevant state is\n\t// (to avoid creating traps per instance to capture the state in closure,\n\t// and to avoid creating weird hidden properties as well)\n\t// So the trick is to use 'state' as the actual 'target'! (and make sure we intercept everything)\n\t// Note that in the case of an array, we put the state in an array to have better Reflect defaults ootb\n\tlet target: T = state as any\n\tlet traps: ProxyHandler> = objectTraps\n\tif (isArray) {\n\t\ttarget = [state] as any\n\t\ttraps = arrayTraps\n\t}\n\n\tconst {revoke, proxy} = Proxy.revocable(target, traps)\n\tstate.draft_ = proxy as any\n\tstate.revoke_ = revoke\n\treturn proxy as any\n}\n\n/**\n * Object drafts\n */\nexport const objectTraps: ProxyHandler = {\n\tget(state, prop) {\n\t\tif (prop === DRAFT_STATE) return state\n\n\t\tconst source = latest(state)\n\t\tif (!has(source, prop)) {\n\t\t\t// non-existing or non-own property...\n\t\t\treturn readPropFromProto(state, source, prop)\n\t\t}\n\t\tconst value = source[prop]\n\t\tif (state.finalized_ || !isDraftable(value)) {\n\t\t\treturn value\n\t\t}\n\t\t// Check for existing draft in modified state.\n\t\t// Assigned values are never drafted. This catches any drafts we created, too.\n\t\tif (value === peek(state.base_, prop)) {\n\t\t\tprepareCopy(state)\n\t\t\treturn (state.copy_![prop as any] = createProxy(\n\t\t\t\tstate.scope_.immer_,\n\t\t\t\tvalue,\n\t\t\t\tstate\n\t\t\t))\n\t\t}\n\t\treturn value\n\t},\n\thas(state, prop) {\n\t\treturn prop in latest(state)\n\t},\n\townKeys(state) {\n\t\treturn Reflect.ownKeys(latest(state))\n\t},\n\tset(\n\t\tstate: ProxyObjectState,\n\t\tprop: string /* strictly not, but helps TS */,\n\t\tvalue\n\t) {\n\t\tconst desc = getDescriptorFromProto(latest(state), prop)\n\t\tif (desc?.set) {\n\t\t\t// special case: if this write is captured by a setter, we have\n\t\t\t// to trigger it with the correct context\n\t\t\tdesc.set.call(state.draft_, value)\n\t\t\treturn true\n\t\t}\n\t\tif (!state.modified_) {\n\t\t\t// the last check is because we need to be able to distinguish setting a non-existing to undefined (which is a change)\n\t\t\t// from setting an existing property with value undefined to undefined (which is not a change)\n\t\t\tconst current = peek(latest(state), prop)\n\t\t\t// special case, if we assigning the original value to a draft, we can ignore the assignment\n\t\t\tconst currentState: ProxyObjectState = current?.[DRAFT_STATE]\n\t\t\tif (currentState && currentState.base_ === value) {\n\t\t\t\tstate.copy_![prop] = value\n\t\t\t\tstate.assigned_[prop] = false\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tif (is(value, current) && (value !== undefined || has(state.base_, prop)))\n\t\t\t\treturn true\n\t\t\tprepareCopy(state)\n\t\t\tmarkChanged(state)\n\t\t}\n\n\t\tif (\n\t\t\t(state.copy_![prop] === value &&\n\t\t\t\t// special case: handle new props with value 'undefined'\n\t\t\t\t(value !== undefined || prop in state.copy_)) ||\n\t\t\t// special case: NaN\n\t\t\t(Number.isNaN(value) && Number.isNaN(state.copy_![prop]))\n\t\t)\n\t\t\treturn true\n\n\t\t// @ts-ignore\n\t\tstate.copy_![prop] = value\n\t\tstate.assigned_[prop] = true\n\t\treturn true\n\t},\n\tdeleteProperty(state, prop: string) {\n\t\t// The `undefined` check is a fast path for pre-existing keys.\n\t\tif (peek(state.base_, prop) !== undefined || prop in state.base_) {\n\t\t\tstate.assigned_[prop] = false\n\t\t\tprepareCopy(state)\n\t\t\tmarkChanged(state)\n\t\t} else {\n\t\t\t// if an originally not assigned property was deleted\n\t\t\tdelete state.assigned_[prop]\n\t\t}\n\t\t// @ts-ignore\n\t\tif (state.copy_) delete state.copy_[prop]\n\t\treturn true\n\t},\n\t// Note: We never coerce `desc.value` into an Immer draft, because we can't make\n\t// the same guarantee in ES5 mode.\n\tgetOwnPropertyDescriptor(state, prop) {\n\t\tconst owner = latest(state)\n\t\tconst desc = Reflect.getOwnPropertyDescriptor(owner, prop)\n\t\tif (!desc) return desc\n\t\treturn {\n\t\t\twritable: true,\n\t\t\tconfigurable: state.type_ !== ProxyType.ProxyArray || prop !== \"length\",\n\t\t\tenumerable: desc.enumerable,\n\t\t\tvalue: owner[prop]\n\t\t}\n\t},\n\tdefineProperty() {\n\t\tdie(11)\n\t},\n\tgetPrototypeOf(state) {\n\t\treturn Object.getPrototypeOf(state.base_)\n\t},\n\tsetPrototypeOf() {\n\t\tdie(12)\n\t}\n}\n\n/**\n * Array drafts\n */\n\nconst arrayTraps: ProxyHandler<[ProxyArrayState]> = {}\neach(objectTraps, (key, fn) => {\n\t// @ts-ignore\n\tarrayTraps[key] = function() {\n\t\targuments[0] = arguments[0][0]\n\t\treturn fn.apply(this, arguments)\n\t}\n})\narrayTraps.deleteProperty = function(state, prop) {\n\tif (__DEV__ && isNaN(parseInt(prop as any))) die(13)\n\t// @ts-ignore\n\treturn arrayTraps.set!.call(this, state, prop, undefined)\n}\narrayTraps.set = function(state, prop, value) {\n\tif (__DEV__ && prop !== \"length\" && isNaN(parseInt(prop as any))) die(14)\n\treturn objectTraps.set!.call(this, state[0], prop, value, state[0])\n}\n\n// Access a property without creating an Immer draft.\nfunction peek(draft: Drafted, prop: PropertyKey) {\n\tconst state = draft[DRAFT_STATE]\n\tconst source = state ? latest(state) : draft\n\treturn source[prop]\n}\n\nfunction readPropFromProto(state: ImmerState, source: any, prop: PropertyKey) {\n\tconst desc = getDescriptorFromProto(source, prop)\n\treturn desc\n\t\t? `value` in desc\n\t\t\t? desc.value\n\t\t\t: // This is a very special case, if the prop is a getter defined by the\n\t\t\t // prototype, we should invoke it with the draft as context!\n\t\t\t desc.get?.call(state.draft_)\n\t\t: undefined\n}\n\nfunction getDescriptorFromProto(\n\tsource: any,\n\tprop: PropertyKey\n): PropertyDescriptor | undefined {\n\t// 'in' checks proto!\n\tif (!(prop in source)) return undefined\n\tlet proto = Object.getPrototypeOf(source)\n\twhile (proto) {\n\t\tconst desc = Object.getOwnPropertyDescriptor(proto, prop)\n\t\tif (desc) return desc\n\t\tproto = Object.getPrototypeOf(proto)\n\t}\n\treturn undefined\n}\n\nexport function markChanged(state: ImmerState) {\n\tif (!state.modified_) {\n\t\tstate.modified_ = true\n\t\tif (state.parent_) {\n\t\t\tmarkChanged(state.parent_)\n\t\t}\n\t}\n}\n\nexport function prepareCopy(state: {base_: any; copy_: any}) {\n\tif (!state.copy_) {\n\t\tstate.copy_ = shallowCopy(state.base_)\n\t}\n}\n", "import {\n\tIProduceWithPatches,\n\tIProduce,\n\tImmerState,\n\tDrafted,\n\tisDraftable,\n\tprocessResult,\n\tPatch,\n\tObjectish,\n\tDRAFT_STATE,\n\tDraft,\n\tPatchListener,\n\tisDraft,\n\tisMap,\n\tisSet,\n\tcreateProxyProxy,\n\tgetPlugin,\n\tdie,\n\thasProxies,\n\tenterScope,\n\trevokeScope,\n\tleaveScope,\n\tusePatchesInScope,\n\tgetCurrentScope,\n\tNOTHING,\n\tfreeze,\n\tcurrent\n} from \"../internal\"\n\ninterface ProducersFns {\n\tproduce: IProduce\n\tproduceWithPatches: IProduceWithPatches\n}\n\nexport class Immer implements ProducersFns {\n\tuseProxies_: boolean = hasProxies\n\n\tautoFreeze_: boolean = true\n\n\tconstructor(config?: {useProxies?: boolean; autoFreeze?: boolean}) {\n\t\tif (typeof config?.useProxies === \"boolean\")\n\t\t\tthis.setUseProxies(config!.useProxies)\n\t\tif (typeof config?.autoFreeze === \"boolean\")\n\t\t\tthis.setAutoFreeze(config!.autoFreeze)\n\t}\n\n\t/**\n\t * The `produce` function takes a value and a \"recipe function\" (whose\n\t * return value often depends on the base state). The recipe function is\n\t * free to mutate its first argument however it wants. All mutations are\n\t * only ever applied to a __copy__ of the base state.\n\t *\n\t * Pass only a function to create a \"curried producer\" which relieves you\n\t * from passing the recipe function every time.\n\t *\n\t * Only plain objects and arrays are made mutable. All other objects are\n\t * considered uncopyable.\n\t *\n\t * Note: This function is __bound__ to its `Immer` instance.\n\t *\n\t * @param {any} base - the initial state\n\t * @param {Function} recipe - function that receives a proxy of the base state as first argument and which can be freely modified\n\t * @param {Function} patchListener - optional function that will be called with all the patches produced here\n\t * @returns {any} a new state, or the initial state if nothing was modified\n\t */\n\tproduce: IProduce = (base: any, recipe?: any, patchListener?: any) => {\n\t\t// curried invocation\n\t\tif (typeof base === \"function\" && typeof recipe !== \"function\") {\n\t\t\tconst defaultBase = recipe\n\t\t\trecipe = base\n\n\t\t\tconst self = this\n\t\t\treturn function curriedProduce(\n\t\t\t\tthis: any,\n\t\t\t\tbase = defaultBase,\n\t\t\t\t...args: any[]\n\t\t\t) {\n\t\t\t\treturn self.produce(base, (draft: Drafted) => recipe.call(this, draft, ...args)) // prettier-ignore\n\t\t\t}\n\t\t}\n\n\t\tif (typeof recipe !== \"function\") die(6)\n\t\tif (patchListener !== undefined && typeof patchListener !== \"function\")\n\t\t\tdie(7)\n\n\t\tlet result\n\n\t\t// Only plain objects, arrays, and \"immerable classes\" are drafted.\n\t\tif (isDraftable(base)) {\n\t\t\tconst scope = enterScope(this)\n\t\t\tconst proxy = createProxy(this, base, undefined)\n\t\t\tlet hasError = true\n\t\t\ttry {\n\t\t\t\tresult = recipe(proxy)\n\t\t\t\thasError = false\n\t\t\t} finally {\n\t\t\t\t// finally instead of catch + rethrow better preserves original stack\n\t\t\t\tif (hasError) revokeScope(scope)\n\t\t\t\telse leaveScope(scope)\n\t\t\t}\n\t\t\tif (typeof Promise !== \"undefined\" && result instanceof Promise) {\n\t\t\t\treturn result.then(\n\t\t\t\t\tresult => {\n\t\t\t\t\t\tusePatchesInScope(scope, patchListener)\n\t\t\t\t\t\treturn processResult(result, scope)\n\t\t\t\t\t},\n\t\t\t\t\terror => {\n\t\t\t\t\t\trevokeScope(scope)\n\t\t\t\t\t\tthrow error\n\t\t\t\t\t}\n\t\t\t\t)\n\t\t\t}\n\t\t\tusePatchesInScope(scope, patchListener)\n\t\t\treturn processResult(result, scope)\n\t\t} else if (!base || typeof base !== \"object\") {\n\t\t\tresult = recipe(base)\n\t\t\tif (result === undefined) result = base\n\t\t\tif (result === NOTHING) result = undefined\n\t\t\tif (this.autoFreeze_) freeze(result, true)\n\t\t\tif (patchListener) {\n\t\t\t\tconst p: Patch[] = []\n\t\t\t\tconst ip: Patch[] = []\n\t\t\t\tgetPlugin(\"Patches\").generateReplacementPatches_(base, result, p, ip)\n\t\t\t\tpatchListener(p, ip)\n\t\t\t}\n\t\t\treturn result\n\t\t} else die(21, base)\n\t}\n\n\tproduceWithPatches: IProduceWithPatches = (base: any, recipe?: any): any => {\n\t\t// curried invocation\n\t\tif (typeof base === \"function\") {\n\t\t\treturn (state: any, ...args: any[]) =>\n\t\t\t\tthis.produceWithPatches(state, (draft: any) => base(draft, ...args))\n\t\t}\n\n\t\tlet patches: Patch[], inversePatches: Patch[]\n\t\tconst result = this.produce(base, recipe, (p: Patch[], ip: Patch[]) => {\n\t\t\tpatches = p\n\t\t\tinversePatches = ip\n\t\t})\n\n\t\tif (typeof Promise !== \"undefined\" && result instanceof Promise) {\n\t\t\treturn result.then(nextState => [nextState, patches!, inversePatches!])\n\t\t}\n\t\treturn [result, patches!, inversePatches!]\n\t}\n\n\tcreateDraft(base: T): Draft {\n\t\tif (!isDraftable(base)) die(8)\n\t\tif (isDraft(base)) base = current(base)\n\t\tconst scope = enterScope(this)\n\t\tconst proxy = createProxy(this, base, undefined)\n\t\tproxy[DRAFT_STATE].isManual_ = true\n\t\tleaveScope(scope)\n\t\treturn proxy as any\n\t}\n\n\tfinishDraft>(\n\t\tdraft: D,\n\t\tpatchListener?: PatchListener\n\t): D extends Draft ? T : never {\n\t\tconst state: ImmerState = draft && (draft as any)[DRAFT_STATE]\n\t\tif (__DEV__) {\n\t\t\tif (!state || !state.isManual_) die(9)\n\t\t\tif (state.finalized_) die(10)\n\t\t}\n\t\tconst {scope_: scope} = state\n\t\tusePatchesInScope(scope, patchListener)\n\t\treturn processResult(undefined, scope)\n\t}\n\n\t/**\n\t * Pass true to automatically freeze all copies created by Immer.\n\t *\n\t * By default, auto-freezing is enabled.\n\t */\n\tsetAutoFreeze(value: boolean) {\n\t\tthis.autoFreeze_ = value\n\t}\n\n\t/**\n\t * Pass true to use the ES2015 `Proxy` class when creating drafts, which is\n\t * always faster than using ES5 proxies.\n\t *\n\t * By default, feature detection is used, so calling this is rarely necessary.\n\t */\n\tsetUseProxies(value: boolean) {\n\t\tif (value && !hasProxies) {\n\t\t\tdie(20)\n\t\t}\n\t\tthis.useProxies_ = value\n\t}\n\n\tapplyPatches(base: T, patches: Patch[]): T {\n\t\t// If a patch replaces the entire state, take that replacement as base\n\t\t// before applying patches\n\t\tlet i: number\n\t\tfor (i = patches.length - 1; i >= 0; i--) {\n\t\t\tconst patch = patches[i]\n\t\t\tif (patch.path.length === 0 && patch.op === \"replace\") {\n\t\t\t\tbase = patch.value\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\t// If there was a patch that replaced the entire state, start from the\n\t\t// patch after that.\n\t\tif (i > -1) {\n\t\t\tpatches = patches.slice(i + 1)\n\t\t}\n\n\t\tconst applyPatchesImpl = getPlugin(\"Patches\").applyPatches_\n\t\tif (isDraft(base)) {\n\t\t\t// N.B: never hits if some patch a replacement, patches are never drafts\n\t\t\treturn applyPatchesImpl(base, patches)\n\t\t}\n\t\t// Otherwise, produce a copy of the base state.\n\t\treturn this.produce(base, (draft: Drafted) =>\n\t\t\tapplyPatchesImpl(draft, patches)\n\t\t)\n\t}\n}\n\nexport function createProxy(\n\timmer: Immer,\n\tvalue: T,\n\tparent?: ImmerState\n): Drafted {\n\t// precondition: createProxy should be guarded by isDraftable, so we know we can safely draft\n\tconst draft: Drafted = isMap(value)\n\t\t? getPlugin(\"MapSet\").proxyMap_(value, parent)\n\t\t: isSet(value)\n\t\t? getPlugin(\"MapSet\").proxySet_(value, parent)\n\t\t: immer.useProxies_\n\t\t? createProxyProxy(value, parent)\n\t\t: getPlugin(\"ES5\").createES5Proxy_(value, parent)\n\n\tconst scope = parent ? parent.scope_ : getCurrentScope()\n\tscope.drafts_.push(draft)\n\treturn draft\n}\n", "import {\n\tdie,\n\tisDraft,\n\tshallowCopy,\n\teach,\n\tDRAFT_STATE,\n\tget,\n\tset,\n\tImmerState,\n\tisDraftable,\n\tArchtype,\n\tgetArchtype,\n\tgetPlugin\n} from \"../internal\"\n\n/** Takes a snapshot of the current state of a draft and finalizes it (but without freezing). This is a great utility to print the current state during debugging (no Proxies in the way). The output of current can also be safely leaked outside the producer. */\nexport function current(value: T): T\nexport function current(value: any): any {\n\tif (!isDraft(value)) die(22, value)\n\treturn currentImpl(value)\n}\n\nfunction currentImpl(value: any): any {\n\tif (!isDraftable(value)) return value\n\tconst state: ImmerState | undefined = value[DRAFT_STATE]\n\tlet copy: any\n\tconst archType = getArchtype(value)\n\tif (state) {\n\t\tif (\n\t\t\t!state.modified_ &&\n\t\t\t(state.type_ < 4 || !getPlugin(\"ES5\").hasChanges_(state as any))\n\t\t)\n\t\t\treturn state.base_\n\t\t// Optimization: avoid generating new drafts during copying\n\t\tstate.finalized_ = true\n\t\tcopy = copyHelper(value, archType)\n\t\tstate.finalized_ = false\n\t} else {\n\t\tcopy = copyHelper(value, archType)\n\t}\n\n\teach(copy, (key, childValue) => {\n\t\tif (state && get(state.base_, key) === childValue) return // no need to copy or search in something that didn't change\n\t\tset(copy, key, currentImpl(childValue))\n\t})\n\t// In the future, we might consider freezing here, based on the current settings\n\treturn archType === Archtype.Set ? new Set(copy) : copy\n}\n\nfunction copyHelper(value: any, archType: number): any {\n\t// creates a shallow copy, even if it is a map or set\n\tswitch (archType) {\n\t\tcase Archtype.Map:\n\t\t\treturn new Map(value)\n\t\tcase Archtype.Set:\n\t\t\t// Set will be cloned as array temporarily, so that we can replace individual items\n\t\t\treturn Array.from(value)\n\t}\n\treturn shallowCopy(value)\n}\n", "import {\n\tImmerState,\n\tDrafted,\n\tES5ArrayState,\n\tES5ObjectState,\n\teach,\n\thas,\n\tisDraft,\n\tlatest,\n\tDRAFT_STATE,\n\tis,\n\tloadPlugin,\n\tImmerScope,\n\tProxyType,\n\tgetCurrentScope,\n\tdie,\n\tmarkChanged,\n\tobjectTraps,\n\townKeys,\n\tgetOwnPropertyDescriptors\n} from \"../internal\"\n\ntype ES5State = ES5ArrayState | ES5ObjectState\n\nexport function enableES5() {\n\tfunction willFinalizeES5_(\n\t\tscope: ImmerScope,\n\t\tresult: any,\n\t\tisReplaced: boolean\n\t) {\n\t\tif (!isReplaced) {\n\t\t\tif (scope.patches_) {\n\t\t\t\tmarkChangesRecursively(scope.drafts_![0])\n\t\t\t}\n\t\t\t// This is faster when we don't care about which attributes changed.\n\t\t\tmarkChangesSweep(scope.drafts_)\n\t\t}\n\t\t// When a child draft is returned, look for changes.\n\t\telse if (\n\t\t\tisDraft(result) &&\n\t\t\t(result[DRAFT_STATE] as ES5State).scope_ === scope\n\t\t) {\n\t\t\tmarkChangesSweep(scope.drafts_)\n\t\t}\n\t}\n\n\tfunction createES5Draft(isArray: boolean, base: any) {\n\t\tif (isArray) {\n\t\t\tconst draft = new Array(base.length)\n\t\t\tfor (let i = 0; i < base.length; i++)\n\t\t\t\tObject.defineProperty(draft, \"\" + i, proxyProperty(i, true))\n\t\t\treturn draft\n\t\t} else {\n\t\t\tconst descriptors = getOwnPropertyDescriptors(base)\n\t\t\tdelete descriptors[DRAFT_STATE as any]\n\t\t\tconst keys = ownKeys(descriptors)\n\t\t\tfor (let i = 0; i < keys.length; i++) {\n\t\t\t\tconst key: any = keys[i]\n\t\t\t\tdescriptors[key] = proxyProperty(\n\t\t\t\t\tkey,\n\t\t\t\t\tisArray || !!descriptors[key].enumerable\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn Object.create(Object.getPrototypeOf(base), descriptors)\n\t\t}\n\t}\n\n\tfunction createES5Proxy_(\n\t\tbase: T,\n\t\tparent?: ImmerState\n\t): Drafted {\n\t\tconst isArray = Array.isArray(base)\n\t\tconst draft = createES5Draft(isArray, base)\n\n\t\tconst state: ES5ObjectState | ES5ArrayState = {\n\t\t\ttype_: isArray ? ProxyType.ES5Array : (ProxyType.ES5Object as any),\n\t\t\tscope_: parent ? parent.scope_ : getCurrentScope(),\n\t\t\tmodified_: false,\n\t\t\tfinalized_: false,\n\t\t\tassigned_: {},\n\t\t\tparent_: parent,\n\t\t\t// base is the object we are drafting\n\t\t\tbase_: base,\n\t\t\t// draft is the draft object itself, that traps all reads and reads from either the base (if unmodified) or copy (if modified)\n\t\t\tdraft_: draft,\n\t\t\tcopy_: null,\n\t\t\trevoked_: false,\n\t\t\tisManual_: false\n\t\t}\n\n\t\tObject.defineProperty(draft, DRAFT_STATE, {\n\t\t\tvalue: state,\n\t\t\t// enumerable: false <- the default\n\t\t\twritable: true\n\t\t})\n\t\treturn draft\n\t}\n\n\t// property descriptors are recycled to make sure we don't create a get and set closure per property,\n\t// but share them all instead\n\tconst descriptors: {[prop: string]: PropertyDescriptor} = {}\n\n\tfunction proxyProperty(\n\t\tprop: string | number,\n\t\tenumerable: boolean\n\t): PropertyDescriptor {\n\t\tlet desc = descriptors[prop]\n\t\tif (desc) {\n\t\t\tdesc.enumerable = enumerable\n\t\t} else {\n\t\t\tdescriptors[prop] = desc = {\n\t\t\t\tconfigurable: true,\n\t\t\t\tenumerable,\n\t\t\t\tget(this: any) {\n\t\t\t\t\tconst state = this[DRAFT_STATE]\n\t\t\t\t\tif (__DEV__) assertUnrevoked(state)\n\t\t\t\t\t// @ts-ignore\n\t\t\t\t\treturn objectTraps.get(state, prop)\n\t\t\t\t},\n\t\t\t\tset(this: any, value) {\n\t\t\t\t\tconst state = this[DRAFT_STATE]\n\t\t\t\t\tif (__DEV__) assertUnrevoked(state)\n\t\t\t\t\t// @ts-ignore\n\t\t\t\t\tobjectTraps.set(state, prop, value)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn desc\n\t}\n\n\t// This looks expensive, but only proxies are visited, and only objects without known changes are scanned.\n\tfunction markChangesSweep(drafts: Drafted[]) {\n\t\t// The natural order of drafts in the `scope` array is based on when they\n\t\t// were accessed. By processing drafts in reverse natural order, we have a\n\t\t// better chance of processing leaf nodes first. When a leaf node is known to\n\t\t// have changed, we can avoid any traversal of its ancestor nodes.\n\t\tfor (let i = drafts.length - 1; i >= 0; i--) {\n\t\t\tconst state: ES5State = drafts[i][DRAFT_STATE]\n\t\t\tif (!state.modified_) {\n\t\t\t\tswitch (state.type_) {\n\t\t\t\t\tcase ProxyType.ES5Array:\n\t\t\t\t\t\tif (hasArrayChanges(state)) markChanged(state)\n\t\t\t\t\t\tbreak\n\t\t\t\t\tcase ProxyType.ES5Object:\n\t\t\t\t\t\tif (hasObjectChanges(state)) markChanged(state)\n\t\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfunction markChangesRecursively(object: any) {\n\t\tif (!object || typeof object !== \"object\") return\n\t\tconst state: ES5State | undefined = object[DRAFT_STATE]\n\t\tif (!state) return\n\t\tconst {base_, draft_, assigned_, type_} = state\n\t\tif (type_ === ProxyType.ES5Object) {\n\t\t\t// Look for added keys.\n\t\t\t// probably there is a faster way to detect changes, as sweep + recurse seems to do some\n\t\t\t// unnecessary work.\n\t\t\t// also: probably we can store the information we detect here, to speed up tree finalization!\n\t\t\teach(draft_, key => {\n\t\t\t\tif ((key as any) === DRAFT_STATE) return\n\t\t\t\t// The `undefined` check is a fast path for pre-existing keys.\n\t\t\t\tif ((base_ as any)[key] === undefined && !has(base_, key)) {\n\t\t\t\t\tassigned_[key] = true\n\t\t\t\t\tmarkChanged(state)\n\t\t\t\t} else if (!assigned_[key]) {\n\t\t\t\t\t// Only untouched properties trigger recursion.\n\t\t\t\t\tmarkChangesRecursively(draft_[key])\n\t\t\t\t}\n\t\t\t})\n\t\t\t// Look for removed keys.\n\t\t\teach(base_, key => {\n\t\t\t\t// The `undefined` check is a fast path for pre-existing keys.\n\t\t\t\tif (draft_[key] === undefined && !has(draft_, key)) {\n\t\t\t\t\tassigned_[key] = false\n\t\t\t\t\tmarkChanged(state)\n\t\t\t\t}\n\t\t\t})\n\t\t} else if (type_ === ProxyType.ES5Array) {\n\t\t\tif (hasArrayChanges(state as ES5ArrayState)) {\n\t\t\t\tmarkChanged(state)\n\t\t\t\tassigned_.length = true\n\t\t\t}\n\n\t\t\tif (draft_.length < base_.length) {\n\t\t\t\tfor (let i = draft_.length; i < base_.length; i++) assigned_[i] = false\n\t\t\t} else {\n\t\t\t\tfor (let i = base_.length; i < draft_.length; i++) assigned_[i] = true\n\t\t\t}\n\n\t\t\t// Minimum count is enough, the other parts has been processed.\n\t\t\tconst min = Math.min(draft_.length, base_.length)\n\n\t\t\tfor (let i = 0; i < min; i++) {\n\t\t\t\t// Only untouched indices trigger recursion.\n\t\t\t\tif (!draft_.hasOwnProperty(i)) {\n\t\t\t\t\tassigned_[i] = true\n\t\t\t\t}\n\t\t\t\tif (assigned_[i] === undefined) markChangesRecursively(draft_[i])\n\t\t\t}\n\t\t}\n\t}\n\n\tfunction hasObjectChanges(state: ES5ObjectState) {\n\t\tconst {base_, draft_} = state\n\n\t\t// Search for added keys and changed keys. Start at the back, because\n\t\t// non-numeric keys are ordered by time of definition on the object.\n\t\tconst keys = ownKeys(draft_)\n\t\tfor (let i = keys.length - 1; i >= 0; i--) {\n\t\t\tconst key: any = keys[i]\n\t\t\tif (key === DRAFT_STATE) continue\n\t\t\tconst baseValue = base_[key]\n\t\t\t// The `undefined` check is a fast path for pre-existing keys.\n\t\t\tif (baseValue === undefined && !has(base_, key)) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\t// Once a base key is deleted, future changes go undetected, because its\n\t\t\t// descriptor is erased. This branch detects any missed changes.\n\t\t\telse {\n\t\t\t\tconst value = draft_[key]\n\t\t\t\tconst state: ImmerState = value && value[DRAFT_STATE]\n\t\t\t\tif (state ? state.base_ !== baseValue : !is(value, baseValue)) {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// At this point, no keys were added or changed.\n\t\t// Compare key count to determine if keys were deleted.\n\t\tconst baseIsDraft = !!base_[DRAFT_STATE as any]\n\t\treturn keys.length !== ownKeys(base_).length + (baseIsDraft ? 0 : 1) // + 1 to correct for DRAFT_STATE\n\t}\n\n\tfunction hasArrayChanges(state: ES5ArrayState) {\n\t\tconst {draft_} = state\n\t\tif (draft_.length !== state.base_.length) return true\n\t\t// See #116\n\t\t// If we first shorten the length, our array interceptors will be removed.\n\t\t// If after that new items are added, result in the same original length,\n\t\t// those last items will have no intercepting property.\n\t\t// So if there is no own descriptor on the last position, we know that items were removed and added\n\t\t// N.B.: splice, unshift, etc only shift values around, but not prop descriptors, so we only have to check\n\t\t// the last one\n\t\t// last descriptor can be not a trap, if the array was extended\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(\n\t\t\tdraft_,\n\t\t\tdraft_.length - 1\n\t\t)\n\t\t// descriptor can be null, but only for newly created sparse arrays, eg. new Array(10)\n\t\tif (descriptor && !descriptor.get) return true\n\t\t// if we miss a property, it has been deleted, so array probobaly changed\n\t\tfor (let i = 0; i < draft_.length; i++) {\n\t\t\tif (!draft_.hasOwnProperty(i)) return true\n\t\t}\n\t\t// For all other cases, we don't have to compare, as they would have been picked up by the index setters\n\t\treturn false\n\t}\n\n\tfunction hasChanges_(state: ES5State) {\n\t\treturn state.type_ === ProxyType.ES5Object\n\t\t\t? hasObjectChanges(state)\n\t\t\t: hasArrayChanges(state)\n\t}\n\n\tfunction assertUnrevoked(state: any /*ES5State | MapState | SetState*/) {\n\t\tif (state.revoked_) die(3, JSON.stringify(latest(state)))\n\t}\n\n\tloadPlugin(\"ES5\", {\n\t\tcreateES5Proxy_,\n\t\twillFinalizeES5_,\n\t\thasChanges_\n\t})\n}\n", "import {immerable} from \"../immer\"\nimport {\n\tImmerState,\n\tPatch,\n\tSetState,\n\tES5ArrayState,\n\tProxyArrayState,\n\tMapState,\n\tES5ObjectState,\n\tProxyObjectState,\n\tPatchPath,\n\tget,\n\teach,\n\thas,\n\tgetArchtype,\n\tisSet,\n\tisMap,\n\tloadPlugin,\n\tProxyType,\n\tArchtype,\n\tdie,\n\tisDraft,\n\tisDraftable,\n\tNOTHING\n} from \"../internal\"\n\nexport function enablePatches() {\n\tconst REPLACE = \"replace\"\n\tconst ADD = \"add\"\n\tconst REMOVE = \"remove\"\n\n\tfunction generatePatches_(\n\t\tstate: ImmerState,\n\t\tbasePath: PatchPath,\n\t\tpatches: Patch[],\n\t\tinversePatches: Patch[]\n\t): void {\n\t\tswitch (state.type_) {\n\t\t\tcase ProxyType.ProxyObject:\n\t\t\tcase ProxyType.ES5Object:\n\t\t\tcase ProxyType.Map:\n\t\t\t\treturn generatePatchesFromAssigned(\n\t\t\t\t\tstate,\n\t\t\t\t\tbasePath,\n\t\t\t\t\tpatches,\n\t\t\t\t\tinversePatches\n\t\t\t\t)\n\t\t\tcase ProxyType.ES5Array:\n\t\t\tcase ProxyType.ProxyArray:\n\t\t\t\treturn generateArrayPatches(state, basePath, patches, inversePatches)\n\t\t\tcase ProxyType.Set:\n\t\t\t\treturn generateSetPatches(\n\t\t\t\t\t(state as any) as SetState,\n\t\t\t\t\tbasePath,\n\t\t\t\t\tpatches,\n\t\t\t\t\tinversePatches\n\t\t\t\t)\n\t\t}\n\t}\n\n\tfunction generateArrayPatches(\n\t\tstate: ES5ArrayState | ProxyArrayState,\n\t\tbasePath: PatchPath,\n\t\tpatches: Patch[],\n\t\tinversePatches: Patch[]\n\t) {\n\t\tlet {base_, assigned_} = state\n\t\tlet copy_ = state.copy_!\n\n\t\t// Reduce complexity by ensuring `base` is never longer.\n\t\tif (copy_.length < base_.length) {\n\t\t\t// @ts-ignore\n\t\t\t;[base_, copy_] = [copy_, base_]\n\t\t\t;[patches, inversePatches] = [inversePatches, patches]\n\t\t}\n\n\t\t// Process replaced indices.\n\t\tfor (let i = 0; i < base_.length; i++) {\n\t\t\tif (assigned_[i] && copy_[i] !== base_[i]) {\n\t\t\t\tconst path = basePath.concat([i])\n\t\t\t\tpatches.push({\n\t\t\t\t\top: REPLACE,\n\t\t\t\t\tpath,\n\t\t\t\t\t// Need to maybe clone it, as it can in fact be the original value\n\t\t\t\t\t// due to the base/copy inversion at the start of this function\n\t\t\t\t\tvalue: clonePatchValueIfNeeded(copy_[i])\n\t\t\t\t})\n\t\t\t\tinversePatches.push({\n\t\t\t\t\top: REPLACE,\n\t\t\t\t\tpath,\n\t\t\t\t\tvalue: clonePatchValueIfNeeded(base_[i])\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\n\t\t// Process added indices.\n\t\tfor (let i = base_.length; i < copy_.length; i++) {\n\t\t\tconst path = basePath.concat([i])\n\t\t\tpatches.push({\n\t\t\t\top: ADD,\n\t\t\t\tpath,\n\t\t\t\t// Need to maybe clone it, as it can in fact be the original value\n\t\t\t\t// due to the base/copy inversion at the start of this function\n\t\t\t\tvalue: clonePatchValueIfNeeded(copy_[i])\n\t\t\t})\n\t\t}\n\t\tif (base_.length < copy_.length) {\n\t\t\tinversePatches.push({\n\t\t\t\top: REPLACE,\n\t\t\t\tpath: basePath.concat([\"length\"]),\n\t\t\t\tvalue: base_.length\n\t\t\t})\n\t\t}\n\t}\n\n\t// This is used for both Map objects and normal objects.\n\tfunction generatePatchesFromAssigned(\n\t\tstate: MapState | ES5ObjectState | ProxyObjectState,\n\t\tbasePath: PatchPath,\n\t\tpatches: Patch[],\n\t\tinversePatches: Patch[]\n\t) {\n\t\tconst {base_, copy_} = state\n\t\teach(state.assigned_!, (key, assignedValue) => {\n\t\t\tconst origValue = get(base_, key)\n\t\t\tconst value = get(copy_!, key)\n\t\t\tconst op = !assignedValue ? REMOVE : has(base_, key) ? REPLACE : ADD\n\t\t\tif (origValue === value && op === REPLACE) return\n\t\t\tconst path = basePath.concat(key as any)\n\t\t\tpatches.push(op === REMOVE ? {op, path} : {op, path, value})\n\t\t\tinversePatches.push(\n\t\t\t\top === ADD\n\t\t\t\t\t? {op: REMOVE, path}\n\t\t\t\t\t: op === REMOVE\n\t\t\t\t\t? {op: ADD, path, value: clonePatchValueIfNeeded(origValue)}\n\t\t\t\t\t: {op: REPLACE, path, value: clonePatchValueIfNeeded(origValue)}\n\t\t\t)\n\t\t})\n\t}\n\n\tfunction generateSetPatches(\n\t\tstate: SetState,\n\t\tbasePath: PatchPath,\n\t\tpatches: Patch[],\n\t\tinversePatches: Patch[]\n\t) {\n\t\tlet {base_, copy_} = state\n\n\t\tlet i = 0\n\t\tbase_.forEach((value: any) => {\n\t\t\tif (!copy_!.has(value)) {\n\t\t\t\tconst path = basePath.concat([i])\n\t\t\t\tpatches.push({\n\t\t\t\t\top: REMOVE,\n\t\t\t\t\tpath,\n\t\t\t\t\tvalue\n\t\t\t\t})\n\t\t\t\tinversePatches.unshift({\n\t\t\t\t\top: ADD,\n\t\t\t\t\tpath,\n\t\t\t\t\tvalue\n\t\t\t\t})\n\t\t\t}\n\t\t\ti++\n\t\t})\n\t\ti = 0\n\t\tcopy_!.forEach((value: any) => {\n\t\t\tif (!base_.has(value)) {\n\t\t\t\tconst path = basePath.concat([i])\n\t\t\t\tpatches.push({\n\t\t\t\t\top: ADD,\n\t\t\t\t\tpath,\n\t\t\t\t\tvalue\n\t\t\t\t})\n\t\t\t\tinversePatches.unshift({\n\t\t\t\t\top: REMOVE,\n\t\t\t\t\tpath,\n\t\t\t\t\tvalue\n\t\t\t\t})\n\t\t\t}\n\t\t\ti++\n\t\t})\n\t}\n\n\tfunction generateReplacementPatches_(\n\t\tbaseValue: any,\n\t\treplacement: any,\n\t\tpatches: Patch[],\n\t\tinversePatches: Patch[]\n\t): void {\n\t\tpatches.push({\n\t\t\top: REPLACE,\n\t\t\tpath: [],\n\t\t\tvalue: replacement === NOTHING ? undefined : replacement\n\t\t})\n\t\tinversePatches.push({\n\t\t\top: REPLACE,\n\t\t\tpath: [],\n\t\t\tvalue: baseValue\n\t\t})\n\t}\n\n\tfunction applyPatches_(draft: T, patches: Patch[]): T {\n\t\tpatches.forEach(patch => {\n\t\t\tconst {path, op} = patch\n\n\t\t\tlet base: any = draft\n\t\t\tfor (let i = 0; i < path.length - 1; i++) {\n\t\t\t\tconst parentType = getArchtype(base)\n\t\t\t\tlet p = path[i]\n\t\t\t\tif (typeof p !== \"string\" && typeof p !== \"number\") {\n\t\t\t\t\tp = \"\" + p\n\t\t\t\t}\n\n\t\t\t\t// See #738, avoid prototype pollution\n\t\t\t\tif (\n\t\t\t\t\t(parentType === Archtype.Object || parentType === Archtype.Array) &&\n\t\t\t\t\t(p === \"__proto__\" || p === \"constructor\")\n\t\t\t\t)\n\t\t\t\t\tdie(24)\n\t\t\t\tif (typeof base === \"function\" && p === \"prototype\") die(24)\n\t\t\t\tbase = get(base, p)\n\t\t\t\tif (typeof base !== \"object\") die(15, path.join(\"/\"))\n\t\t\t}\n\n\t\t\tconst type = getArchtype(base)\n\t\t\tconst value = deepClonePatchValue(patch.value) // used to clone patch to ensure original patch is not modified, see #411\n\t\t\tconst key = path[path.length - 1]\n\t\t\tswitch (op) {\n\t\t\t\tcase REPLACE:\n\t\t\t\t\tswitch (type) {\n\t\t\t\t\t\tcase Archtype.Map:\n\t\t\t\t\t\t\treturn base.set(key, value)\n\t\t\t\t\t\t/* istanbul ignore next */\n\t\t\t\t\t\tcase Archtype.Set:\n\t\t\t\t\t\t\tdie(16)\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t// if value is an object, then it's assigned by reference\n\t\t\t\t\t\t\t// in the following add or remove ops, the value field inside the patch will also be modifyed\n\t\t\t\t\t\t\t// so we use value from the cloned patch\n\t\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\t\treturn (base[key] = value)\n\t\t\t\t\t}\n\t\t\t\tcase ADD:\n\t\t\t\t\tswitch (type) {\n\t\t\t\t\t\tcase Archtype.Array:\n\t\t\t\t\t\t\treturn key === \"-\"\n\t\t\t\t\t\t\t\t? base.push(value)\n\t\t\t\t\t\t\t\t: base.splice(key as any, 0, value)\n\t\t\t\t\t\tcase Archtype.Map:\n\t\t\t\t\t\t\treturn base.set(key, value)\n\t\t\t\t\t\tcase Archtype.Set:\n\t\t\t\t\t\t\treturn base.add(value)\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\treturn (base[key] = value)\n\t\t\t\t\t}\n\t\t\t\tcase REMOVE:\n\t\t\t\t\tswitch (type) {\n\t\t\t\t\t\tcase Archtype.Array:\n\t\t\t\t\t\t\treturn base.splice(key as any, 1)\n\t\t\t\t\t\tcase Archtype.Map:\n\t\t\t\t\t\t\treturn base.delete(key)\n\t\t\t\t\t\tcase Archtype.Set:\n\t\t\t\t\t\t\treturn base.delete(patch.value)\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\treturn delete base[key]\n\t\t\t\t\t}\n\t\t\t\tdefault:\n\t\t\t\t\tdie(17, op)\n\t\t\t}\n\t\t})\n\n\t\treturn draft\n\t}\n\n\t// optimize: this is quite a performance hit, can we detect intelligently when it is needed?\n\t// E.g. auto-draft when new objects from outside are assigned and modified?\n\t// (See failing test when deepClone just returns obj)\n\tfunction deepClonePatchValue(obj: T): T\n\tfunction deepClonePatchValue(obj: any) {\n\t\tif (!isDraftable(obj)) return obj\n\t\tif (Array.isArray(obj)) return obj.map(deepClonePatchValue)\n\t\tif (isMap(obj))\n\t\t\treturn new Map(\n\t\t\t\tArray.from(obj.entries()).map(([k, v]) => [k, deepClonePatchValue(v)])\n\t\t\t)\n\t\tif (isSet(obj)) return new Set(Array.from(obj).map(deepClonePatchValue))\n\t\tconst cloned = Object.create(Object.getPrototypeOf(obj))\n\t\tfor (const key in obj) cloned[key] = deepClonePatchValue(obj[key])\n\t\tif (has(obj, immerable)) cloned[immerable] = obj[immerable]\n\t\treturn cloned\n\t}\n\n\tfunction clonePatchValueIfNeeded(obj: T): T {\n\t\tif (isDraft(obj)) {\n\t\t\treturn deepClonePatchValue(obj)\n\t\t} else return obj\n\t}\n\n\tloadPlugin(\"Patches\", {\n\t\tapplyPatches_,\n\t\tgeneratePatches_,\n\t\tgenerateReplacementPatches_\n\t})\n}\n", "// types only!\nimport {\n\tImmerState,\n\tAnyMap,\n\tAnySet,\n\tMapState,\n\tSetState,\n\tDRAFT_STATE,\n\tgetCurrentScope,\n\tlatest,\n\titeratorSymbol,\n\tisDraftable,\n\tcreateProxy,\n\tloadPlugin,\n\tmarkChanged,\n\tProxyType,\n\tdie,\n\teach\n} from \"../internal\"\n\nexport function enableMapSet() {\n\t/* istanbul ignore next */\n\tvar extendStatics = function(d: any, b: any): any {\n\t\textendStatics =\n\t\t\tObject.setPrototypeOf ||\n\t\t\t({__proto__: []} instanceof Array &&\n\t\t\t\tfunction(d, b) {\n\t\t\t\t\td.__proto__ = b\n\t\t\t\t}) ||\n\t\t\tfunction(d, b) {\n\t\t\t\tfor (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]\n\t\t\t}\n\t\treturn extendStatics(d, b)\n\t}\n\n\t// Ugly hack to resolve #502 and inherit built in Map / Set\n\tfunction __extends(d: any, b: any): any {\n\t\textendStatics(d, b)\n\t\tfunction __(this: any): any {\n\t\t\tthis.constructor = d\n\t\t}\n\t\td.prototype =\n\t\t\t// @ts-ignore\n\t\t\t((__.prototype = b.prototype), new __())\n\t}\n\n\tconst DraftMap = (function(_super) {\n\t\t__extends(DraftMap, _super)\n\t\t// Create class manually, cause #502\n\t\tfunction DraftMap(this: any, target: AnyMap, parent?: ImmerState): any {\n\t\t\tthis[DRAFT_STATE] = {\n\t\t\t\ttype_: ProxyType.Map,\n\t\t\t\tparent_: parent,\n\t\t\t\tscope_: parent ? parent.scope_ : getCurrentScope()!,\n\t\t\t\tmodified_: false,\n\t\t\t\tfinalized_: false,\n\t\t\t\tcopy_: undefined,\n\t\t\t\tassigned_: undefined,\n\t\t\t\tbase_: target,\n\t\t\t\tdraft_: this as any,\n\t\t\t\tisManual_: false,\n\t\t\t\trevoked_: false\n\t\t\t} as MapState\n\t\t\treturn this\n\t\t}\n\t\tconst p = DraftMap.prototype\n\n\t\tObject.defineProperty(p, \"size\", {\n\t\t\tget: function() {\n\t\t\t\treturn latest(this[DRAFT_STATE]).size\n\t\t\t}\n\t\t\t// enumerable: false,\n\t\t\t// configurable: true\n\t\t})\n\n\t\tp.has = function(key: any): boolean {\n\t\t\treturn latest(this[DRAFT_STATE]).has(key)\n\t\t}\n\n\t\tp.set = function(key: any, value: any) {\n\t\t\tconst state: MapState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tif (!latest(state).has(key) || latest(state).get(key) !== value) {\n\t\t\t\tprepareMapCopy(state)\n\t\t\t\tmarkChanged(state)\n\t\t\t\tstate.assigned_!.set(key, true)\n\t\t\t\tstate.copy_!.set(key, value)\n\t\t\t\tstate.assigned_!.set(key, true)\n\t\t\t}\n\t\t\treturn this\n\t\t}\n\n\t\tp.delete = function(key: any): boolean {\n\t\t\tif (!this.has(key)) {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\tconst state: MapState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tprepareMapCopy(state)\n\t\t\tmarkChanged(state)\n\t\t\tif (state.base_.has(key)) {\n\t\t\t\tstate.assigned_!.set(key, false)\n\t\t\t} else {\n\t\t\t\tstate.assigned_!.delete(key)\n\t\t\t}\n\t\t\tstate.copy_!.delete(key)\n\t\t\treturn true\n\t\t}\n\n\t\tp.clear = function() {\n\t\t\tconst state: MapState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tif (latest(state).size) {\n\t\t\t\tprepareMapCopy(state)\n\t\t\t\tmarkChanged(state)\n\t\t\t\tstate.assigned_ = new Map()\n\t\t\t\teach(state.base_, key => {\n\t\t\t\t\tstate.assigned_!.set(key, false)\n\t\t\t\t})\n\t\t\t\tstate.copy_!.clear()\n\t\t\t}\n\t\t}\n\n\t\tp.forEach = function(\n\t\t\tcb: (value: any, key: any, self: any) => void,\n\t\t\tthisArg?: any\n\t\t) {\n\t\t\tconst state: MapState = this[DRAFT_STATE]\n\t\t\tlatest(state).forEach((_value: any, key: any, _map: any) => {\n\t\t\t\tcb.call(thisArg, this.get(key), key, this)\n\t\t\t})\n\t\t}\n\n\t\tp.get = function(key: any): any {\n\t\t\tconst state: MapState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tconst value = latest(state).get(key)\n\t\t\tif (state.finalized_ || !isDraftable(value)) {\n\t\t\t\treturn value\n\t\t\t}\n\t\t\tif (value !== state.base_.get(key)) {\n\t\t\t\treturn value // either already drafted or reassigned\n\t\t\t}\n\t\t\t// despite what it looks, this creates a draft only once, see above condition\n\t\t\tconst draft = createProxy(state.scope_.immer_, value, state)\n\t\t\tprepareMapCopy(state)\n\t\t\tstate.copy_!.set(key, draft)\n\t\t\treturn draft\n\t\t}\n\n\t\tp.keys = function(): IterableIterator {\n\t\t\treturn latest(this[DRAFT_STATE]).keys()\n\t\t}\n\n\t\tp.values = function(): IterableIterator {\n\t\t\tconst iterator = this.keys()\n\t\t\treturn {\n\t\t\t\t[iteratorSymbol]: () => this.values(),\n\t\t\t\tnext: () => {\n\t\t\t\t\tconst r = iterator.next()\n\t\t\t\t\t/* istanbul ignore next */\n\t\t\t\t\tif (r.done) return r\n\t\t\t\t\tconst value = this.get(r.value)\n\t\t\t\t\treturn {\n\t\t\t\t\t\tdone: false,\n\t\t\t\t\t\tvalue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} as any\n\t\t}\n\n\t\tp.entries = function(): IterableIterator<[any, any]> {\n\t\t\tconst iterator = this.keys()\n\t\t\treturn {\n\t\t\t\t[iteratorSymbol]: () => this.entries(),\n\t\t\t\tnext: () => {\n\t\t\t\t\tconst r = iterator.next()\n\t\t\t\t\t/* istanbul ignore next */\n\t\t\t\t\tif (r.done) return r\n\t\t\t\t\tconst value = this.get(r.value)\n\t\t\t\t\treturn {\n\t\t\t\t\t\tdone: false,\n\t\t\t\t\t\tvalue: [r.value, value]\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} as any\n\t\t}\n\n\t\tp[iteratorSymbol] = function() {\n\t\t\treturn this.entries()\n\t\t}\n\n\t\treturn DraftMap\n\t})(Map)\n\n\tfunction proxyMap_(target: T, parent?: ImmerState): T {\n\t\t// @ts-ignore\n\t\treturn new DraftMap(target, parent)\n\t}\n\n\tfunction prepareMapCopy(state: MapState) {\n\t\tif (!state.copy_) {\n\t\t\tstate.assigned_ = new Map()\n\t\t\tstate.copy_ = new Map(state.base_)\n\t\t}\n\t}\n\n\tconst DraftSet = (function(_super) {\n\t\t__extends(DraftSet, _super)\n\t\t// Create class manually, cause #502\n\t\tfunction DraftSet(this: any, target: AnySet, parent?: ImmerState) {\n\t\t\tthis[DRAFT_STATE] = {\n\t\t\t\ttype_: ProxyType.Set,\n\t\t\t\tparent_: parent,\n\t\t\t\tscope_: parent ? parent.scope_ : getCurrentScope()!,\n\t\t\t\tmodified_: false,\n\t\t\t\tfinalized_: false,\n\t\t\t\tcopy_: undefined,\n\t\t\t\tbase_: target,\n\t\t\t\tdraft_: this,\n\t\t\t\tdrafts_: new Map(),\n\t\t\t\trevoked_: false,\n\t\t\t\tisManual_: false\n\t\t\t} as SetState\n\t\t\treturn this\n\t\t}\n\t\tconst p = DraftSet.prototype\n\n\t\tObject.defineProperty(p, \"size\", {\n\t\t\tget: function() {\n\t\t\t\treturn latest(this[DRAFT_STATE]).size\n\t\t\t}\n\t\t\t// enumerable: true,\n\t\t})\n\n\t\tp.has = function(value: any): boolean {\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\t// bit of trickery here, to be able to recognize both the value, and the draft of its value\n\t\t\tif (!state.copy_) {\n\t\t\t\treturn state.base_.has(value)\n\t\t\t}\n\t\t\tif (state.copy_.has(value)) return true\n\t\t\tif (state.drafts_.has(value) && state.copy_.has(state.drafts_.get(value)))\n\t\t\t\treturn true\n\t\t\treturn false\n\t\t}\n\n\t\tp.add = function(value: any): any {\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tif (!this.has(value)) {\n\t\t\t\tprepareSetCopy(state)\n\t\t\t\tmarkChanged(state)\n\t\t\t\tstate.copy_!.add(value)\n\t\t\t}\n\t\t\treturn this\n\t\t}\n\n\t\tp.delete = function(value: any): any {\n\t\t\tif (!this.has(value)) {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tprepareSetCopy(state)\n\t\t\tmarkChanged(state)\n\t\t\treturn (\n\t\t\t\tstate.copy_!.delete(value) ||\n\t\t\t\t(state.drafts_.has(value)\n\t\t\t\t\t? state.copy_!.delete(state.drafts_.get(value))\n\t\t\t\t\t: /* istanbul ignore next */ false)\n\t\t\t)\n\t\t}\n\n\t\tp.clear = function() {\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tif (latest(state).size) {\n\t\t\t\tprepareSetCopy(state)\n\t\t\t\tmarkChanged(state)\n\t\t\t\tstate.copy_!.clear()\n\t\t\t}\n\t\t}\n\n\t\tp.values = function(): IterableIterator {\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tprepareSetCopy(state)\n\t\t\treturn state.copy_!.values()\n\t\t}\n\n\t\tp.entries = function entries(): IterableIterator<[any, any]> {\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tprepareSetCopy(state)\n\t\t\treturn state.copy_!.entries()\n\t\t}\n\n\t\tp.keys = function(): IterableIterator {\n\t\t\treturn this.values()\n\t\t}\n\n\t\tp[iteratorSymbol] = function() {\n\t\t\treturn this.values()\n\t\t}\n\n\t\tp.forEach = function forEach(cb: any, thisArg?: any) {\n\t\t\tconst iterator = this.values()\n\t\t\tlet result = iterator.next()\n\t\t\twhile (!result.done) {\n\t\t\t\tcb.call(thisArg, result.value, result.value, this)\n\t\t\t\tresult = iterator.next()\n\t\t\t}\n\t\t}\n\n\t\treturn DraftSet\n\t})(Set)\n\n\tfunction proxySet_(target: T, parent?: ImmerState): T {\n\t\t// @ts-ignore\n\t\treturn new DraftSet(target, parent)\n\t}\n\n\tfunction prepareSetCopy(state: SetState) {\n\t\tif (!state.copy_) {\n\t\t\t// create drafts for all entries to preserve insertion order\n\t\t\tstate.copy_ = new Set()\n\t\t\tstate.base_.forEach(value => {\n\t\t\t\tif (isDraftable(value)) {\n\t\t\t\t\tconst draft = createProxy(state.scope_.immer_, value, state)\n\t\t\t\t\tstate.drafts_.set(value, draft)\n\t\t\t\t\tstate.copy_!.add(draft)\n\t\t\t\t} else {\n\t\t\t\t\tstate.copy_!.add(value)\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t}\n\n\tfunction assertUnrevoked(state: any /*ES5State | MapState | SetState*/) {\n\t\tif (state.revoked_) die(3, JSON.stringify(latest(state)))\n\t}\n\n\tloadPlugin(\"MapSet\", {proxyMap_, proxySet_})\n}\n", "import {enableES5} from \"./es5\"\nimport {enableMapSet} from \"./mapset\"\nimport {enablePatches} from \"./patches\"\n\nexport function enableAllPlugins() {\n\tenableES5()\n\tenableMapSet()\n\tenablePatches()\n}\n", "import {\n\tIProduce,\n\tIProduceWithPatches,\n\tImmer,\n\tDraft,\n\tImmutable\n} from \"./internal\"\n\nexport {\n\tDraft,\n\tImmutable,\n\tPatch,\n\tPatchListener,\n\toriginal,\n\tcurrent,\n\tisDraft,\n\tisDraftable,\n\tNOTHING as nothing,\n\tDRAFTABLE as immerable,\n\tfreeze\n} from \"./internal\"\n\nconst immer = new Immer()\n\n/**\n * The `produce` function takes a value and a \"recipe function\" (whose\n * return value often depends on the base state). The recipe function is\n * free to mutate its first argument however it wants. All mutations are\n * only ever applied to a __copy__ of the base state.\n *\n * Pass only a function to create a \"curried producer\" which relieves you\n * from passing the recipe function every time.\n *\n * Only plain objects and arrays are made mutable. All other objects are\n * considered uncopyable.\n *\n * Note: This function is __bound__ to its `Immer` instance.\n *\n * @param {any} base - the initial state\n * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified\n * @param {Function} patchListener - optional function that will be called with all the patches produced here\n * @returns {any} a new state, or the initial state if nothing was modified\n */\nexport const produce: IProduce = immer.produce\nexport default produce\n\n/**\n * Like `produce`, but `produceWithPatches` always returns a tuple\n * [nextState, patches, inversePatches] (instead of just the next state)\n */\nexport const produceWithPatches: IProduceWithPatches = immer.produceWithPatches.bind(\n\timmer\n)\n\n/**\n * Pass true to automatically freeze all copies created by Immer.\n *\n * Always freeze by default, even in production mode\n */\nexport const setAutoFreeze = immer.setAutoFreeze.bind(immer)\n\n/**\n * Pass true to use the ES2015 `Proxy` class when creating drafts, which is\n * always faster than using ES5 proxies.\n *\n * By default, feature detection is used, so calling this is rarely necessary.\n */\nexport const setUseProxies = immer.setUseProxies.bind(immer)\n\n/**\n * Apply an array of Immer patches to the first argument.\n *\n * This function is a producer, which means copy-on-write is in effect.\n */\nexport const applyPatches = immer.applyPatches.bind(immer)\n\n/**\n * Create an Immer draft from the given base state, which may be a draft itself.\n * The draft can be modified until you finalize it with the `finishDraft` function.\n */\nexport const createDraft = immer.createDraft.bind(immer)\n\n/**\n * Finalize an Immer draft from a `createDraft` call, returning the base state\n * (if no changes were made) or a modified copy. The draft must *not* be\n * mutated afterwards.\n *\n * Pass a function as the 2nd argument to generate Immer patches based on the\n * changes that were made.\n */\nexport const finishDraft = immer.finishDraft.bind(immer)\n\n/**\n * This function is actually a no-op, but can be used to cast an immutable type\n * to an draft type and make TypeScript happy\n *\n * @param value\n */\nexport function castDraft(value: T): Draft {\n\treturn value as any\n}\n\n/**\n * This function is actually a no-op, but can be used to cast a mutable type\n * to an immutable type and make TypeScript happy\n * @param value\n */\nexport function castImmutable(value: T): Immutable {\n\treturn value as any\n}\n\nexport {Immer}\n\nexport {enableES5} from \"./plugins/es5\"\nexport {enablePatches} from \"./plugins/patches\"\nexport {enableMapSet} from \"./plugins/mapset\"\nexport {enableAllPlugins} from \"./plugins/all\"\n", "// Should be no imports here!\n\n// Some things that should be evaluated before all else...\n\n// We only want to know if non-polyfilled symbols are available\nconst hasSymbol =\n\ttypeof Symbol !== \"undefined\" && typeof Symbol(\"x\") === \"symbol\"\nexport const hasMap = typeof Map !== \"undefined\"\nexport const hasSet = typeof Set !== \"undefined\"\nexport const hasProxies =\n\ttypeof Proxy !== \"undefined\" &&\n\ttypeof Proxy.revocable !== \"undefined\" &&\n\ttypeof Reflect !== \"undefined\"\n\n/**\n * The sentinel value returned by producers to replace the draft with undefined.\n */\nexport const NOTHING: Nothing = hasSymbol\n\t? Symbol.for(\"immer-nothing\")\n\t: ({[\"immer-nothing\"]: true} as any)\n\n/**\n * To let Immer treat your class instances as plain immutable objects\n * (albeit with a custom prototype), you must define either an instance property\n * or a static property on each of your custom classes.\n *\n * Otherwise, your class instance will never be drafted, which means it won't be\n * safe to mutate in a produce callback.\n */\nexport const DRAFTABLE: unique symbol = hasSymbol\n\t? Symbol.for(\"immer-draftable\")\n\t: (\"__$immer_draftable\" as any)\n\nexport const DRAFT_STATE: unique symbol = hasSymbol\n\t? Symbol.for(\"immer-state\")\n\t: (\"__$immer_state\" as any)\n\n// Even a polyfilled Symbol might provide Symbol.iterator\nexport const iteratorSymbol: typeof Symbol.iterator =\n\t(typeof Symbol != \"undefined\" && Symbol.iterator) || (\"@@iterator\" as any)\n\n/** Use a class type for `nothing` so its type is unique */\nexport class Nothing {\n\t// This lets us do `Exclude`\n\t// @ts-ignore\n\tprivate _!: unique symbol\n}\n", "import {LotsViewModes_Enum} from \"./rematch/models/currentAuctionLotsModel\";\n\n\nexport type NextLotJSDATA_TypeDef = Partial<{\n app_env: string,\n rails_env: string,\n\n load_admin_dashboard?: boolean,\n\n limits: {\n transloadit_max_file_size_megabytes: number,\n transloadit_max_zip_file_size_megabytes: number,\n inventory_refno_min_length: number,\n\n name_max_length: number,\n description_max_length: number,\n\n },\n\n pusher: {\n app_id: string,\n app_key: string,\n cluster: string,\n },\n\n webapp_root_base_url:string,\n webapp_root_path: string,\n webapp_bidder_login_url: string,\n\n frontend_api_base_url:string,\n cardpointe_tokenizer_api_base_url:string,\n\n bidder_id?:number|null,\n bidder_token?:string|null,\n bidder_first_name?:string|null,\n bidder_last_name?:string|null,\n bidder_email?:string|null,\n bidder_phone_number?:string|null,\n bidder_notification_sms_auction_timeline_enabled?:boolean,\n bidder_phone_number_may_receive_sms?:boolean,\n\n default_clerk_increments: [],\n\n site_id:number,\n site_name:string,\n site_name_short:string,\n site_timezone_name: string,\n site_domain: string,\n site_homepage_banner: string,\n site_support_phone: string,\n site_tech_support_phone: string,\n site_logo_image_url: string,\n site_initial_catalog_lots_view_mode: LotsViewModes_Enum,\n webcast_viewer_signup_reminder_enabled: boolean,\n site_notification_sms_auction_timeline_enabled?:boolean\n} & {\n\n current_admin: {\n id: number,\n email: string,\n },\n current_site?: {\n id: number,\n name: string,\n name_short: string,\n business_address_country_code: string,\n },\n\n form_authenticity_token: string,\n\n urls: {\n ajax_inventory_search: string,\n ajax_lots_fetch_inventory_item_status: string,\n ajax_item_media_file_create: string,\n },\n\n filter_webcast_round_type_ids: Array | [],\n\n data_auction_rings: any,\n data_linked_lots_groups: any,\n\n\n transloadit: {\n params: {\n auth: {\n key: string,\n expires?: string\n },\n steps?: { [step: string]: Record },\n notify_url?: string\n }\n signature: string,\n encoding_steps: any,\n },\n\n\n // via gon from SiteAdm::LotsController\n dromo_user: {\n id: string\n companyId: string\n companyName: string\n }\n dromo_settings: {\n title: string\n webhookUrl?: string\n }\n\n\n // via gon.global from DromoService::APIDataMappings\n dromo: {\n\n frontend_api_key: string,\n\n fields_keys: {\n inventory_refno: string,\n inventory_item_name: string,\n inventory_item_description: string,\n inventory_item_quantity: string,\n inventory_item_video_url: string,\n\n inventory_item_imgurl_strategy: string,\n inventory_item_imgurl_variants: string,\n inventory_item_imgs_urls: string,\n\n lot_number: string,\n lot_starting_bid_amount: string,\n lot_reserve_price: string,\n lot_buy_now_price: string,\n lot_link_name: string,\n lot_custom_sort: string,\n lot_invoice_tax_rate_code: string,\n lot_invoice_buyer_premium_not_taxable: string,\n lot_invoice_item_restricted_online_payment: string,\n lot_invoice_fee_1_description: string,\n lot_invoice_fee_1_amount: string,\n lot_invoice_fee_1_tax_rate_code: string,\n lot_invoice_fee_2_description: string,\n lot_invoice_fee_2_amount: string,\n lot_invoice_fee_2_tax_rate_code: string,\n\n lot_bid_max_amount: string,\n lot_bid_bidder_number: string,\n\n bidder_email: string,\n bidder_first_name: string,\n bidder_last_name: string,\n bidder_phone_number: string,\n bidder_alternate_phone_number: string,\n bidder_billing_company_name: string,\n bidder_billing_company_taxid: string,\n bidder_address_address_street: string,\n bidder_address_address_street2: string,\n bidder_address_city: string,\n bidder_address_region: string,\n bidder_address_postal_code: string,\n bidder_address_country_code: string,\n bidder_credit_card_exempt: string,\n bidder_bidding_globally_approved: string,\n }\n bulk_import_types_ids: {\n bidders: number,\n inventory_items: number,\n lots_with_refno: number,\n lots_no_refno: number,\n place_bids: number\n }\n }\n\n\n country_alpha2_codes: Array,\n\n froala_key: string,\n\n webcast_state_is_preparing: boolean,\n auction_is_before_prebid_closed: boolean,\n}>;\n\n\n\nconst NextLotJSDATA:NextLotJSDATA_TypeDef = {\n ... ((window as any).gon_NextLotJSDATA as any)?.global,\n ... ((window as any).gon_NextLotJSDATA),\n};\n// @ts-ignore\ndelete NextLotJSDATA.global;\n\nexport default NextLotJSDATA;\n\n\nconsole.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> NextLotJSDATA:', NextLotJSDATA);\n\n", "\nexport enum ApiResourceDetailsLevelsEnum {\n metal = 'metal',\n minimal = 'minimal',\n full= 'full',\n}\n\n\nexport type ApiRequestParams_pagination = {\n page_number?: number,\n page_size?: number\n}\n\n\nexport type ApiRequestParams_detailsLevel = {\n details_level?: ApiResourceDetailsLevelsEnum,\n}\n\nexport type ApiRequestParams_auctionsList = ApiRequestParams_detailsLevel & {\n page_number?: number,\n page_size?: number,\n completes_at?: -1|1\n}\n\n\n\nexport type ApiRequestParams_lotsListBrowse = ApiRequestParams_pagination & ApiRequestParams_detailsLevel & {\n sorting_criteria?: string,\n filters?: string\n}\n\nexport type ApiRequestParams_lotsSearch = ApiRequestParams_lotsListBrowse & {\n auction_completes_at?: number\n}\n\n\n\n\n\ntype ApiBaseResource = {\n id: number,\n _class: string,\n created_at: number,\n updated_at?: number,\n}\n\nexport type ApiPaginatedList = {\n _class: 'PaginatedList',\n\n total_count: number,\n page_size: number,\n page_number: number, // starts at 1 (one)\n pages_count: number,\n\n data: Array,\n\n extra: null | {\n sorting_criteria?: string,\n filters?: string,\n ref_timestamp?: number,\n }\n} & T_SupplementalFields\n\n\nexport type ApiLotsRunningTimedStaggeredList = {\n total_count: number,\n window_count?: number,\n ref_timestamp: number,\n cursor_timestamp: number,\n next_cursor_timestamp: number,\n data: Array,\n}\n\n\n\n\n\nexport enum AuctionBiddingApprovalModeCode_Enum {\n manual = 'manual',\n auto_auction = 'auto_auction',\n}\n\n\nexport enum BiddingWarrantStateCode_Enum {\n allowed = 'allowed',\n declined = 'declined',\n pending = 'pending',\n must_accept_terms = 'must_accept_terms',\n must_request = 'must_request',\n must_setup_account = 'must_setup_account',\n must_setup_card = 'must_setup_card',\n}\n\n\nexport enum AuctionSegmentTypeCode_Enum {\n online = 'online',\n webcast = 'webcast',\n}\n\n\nexport enum AuctionTimelineStateCode_Enum {\n completed = 'completed',\n running_stalled = 'running_stalled',\n running_live = 'running_live',\n upcoming = 'upcoming',\n}\n\nexport enum AuctionTimelineStateCodeID_Enum {\n completed = 500,\n running_stalled = 310,\n running_live = 330,\n upcoming = 100,\n}\n\n\nexport enum ItemMediaTypeCodeID_Enum {\n image = 10,\n video_youtube = 21,\n video_vimeo = 22,\n}\n\nexport enum LotReserveStatusCode_Enum {\n no_reserve = 'no_reserve',\n reserve_not_met = 'reserve_not_met',\n reserve_met = 'reserve_met',\n}\n\n\n\nexport type ApiResource_Auction = ApiBaseResource & {\n _class: 'Auction',\n\n site_id: number,\n\n auction_type_id: number,\n\n name: string,\n\n summary_html?: string,\n location_info_text?: string,\n viewing_info_text?: string,\n\n internet_buyer_premium_display_text?: string,\n onsite_buyer_premium_display_text?: string,\n\n details_page_html?: string,\n\n url_thumb_image: string,\n\n auction_timezone_name: string,\n\n starts_at: number,\n closing_starts_at: number,\n closing_ends_at: number,\n webcast_starts_at: number,\n completes_at: number,\n is_completed: boolean,\n\n timeline_state_id: number,\n current_segment_type_code: AuctionSegmentTypeCode_Enum,\n\n lots_count: number,\n\n currency_code: string,\n\n auction_ring_id?: number,\n auction_ring_name?: string,\n\n bidding_approval_mode_code: AuctionBiddingApprovalModeCode_Enum,\n bid_request_note_text: null|string,\n\n bid_increments_table: Array>,\n\n my_bidding_warrant_state_code?: BiddingWarrantStateCode_Enum,\n notification_sms_auction_timeline_enabled?: boolean,\n\n timed_jump_bids_allowed?: boolean,\n timed_bidding_extension?: number,\n timed_lots_staggering_ruleset?: {\n s1_group_size: number,\n s1_time_offset_seconds: number,\n s1_last_lot_number?: string,\n s2_group_size?: number,\n s2_time_offset_seconds?: number,\n },\n\n webcast_is_prepared: boolean,\n enter_webcast_screen_applink_url?: string,\n};\n\n\n\nexport type ApiResource_LotMetal = ApiBaseResource & Partial<{\n\n auction_id: number,\n auction_timezone_name: string,\n\n number: string,\n number_sort: string,\n\n closes_at: number,\n completes_at: number,\n is_completed: boolean,\n has_round: boolean,\n\n linked_lots_group_id: null|number,\n\n inventory_item_id: number,\n\n inventory_refno: string,\n name: string,\n description_html: string,\n quantity: number,\n\n custom_sort: number,\n\n focal_media_file_url_thumb_image: string,\n video_url_thumb_image: string,\n video_url: string,\n\n bids_count: number,\n\n my_bid_is_leading_bid?: boolean,\n leading_bid_amount_cents: number,\n leading_bid_bidder_number: string,\n leading_bid_bidder_label: string,\n\n reserve_price_status_code?: string,\n\n starting_bid_amount_cents?: number,\n asking_bid_amount_cents?: number,\n\n my_max_bid_amount_cents?: number,\n my_bid_exists_in_history?: boolean,\n\n my_watched?: boolean,\n}>;\n\n\nexport type ApiResource_CatalogLot = ApiResource_LotMetal & {\n auction?: ApiResource_Auction,\n}\n\n\nexport type ApiResource_RunningTimedLot = Required & {\n _class: 'RunningTimedLot',\n}\n\nexport type ApiResource_WatchlistRunningLot = ApiBaseResource & Partial & {\n _class: 'WatchlistRunningLot',\n auction: ApiResource_Auction,\n}\n\nexport type ApiResource_SiteSearchLot = ApiBaseResource & Partial & {\n _class: 'SiteSearchLot',\n auction: ApiResource_Auction,\n}\n\nexport type ApiResource_WebcastLot = ApiBaseResource & {\n _class: 'WebcastLot',\n\n auction_id: number,\n\n number: string,\n\n name: string,\n\n description_html: string,\n\n focal_media_file_url_thumb_image: string,\n\n // FIXME: TODO: remove these from this response, and use separate API call for images\n video_url_thumb_image: string,\n video_url: string,\n images: Array<{ url: string, url_thumb: string }>,\n}\n\n\n\nexport type ApiResource_ItemMediaFile_TypeDef = ApiBaseResource & {\n _class: \"ItemMediaFile\",\n\n ext_key: string,\n\n media_type_id: number,\n\n sort_idx: number,\n\n url: string,\n url_thumb_image: string,\n url_high_def: string,\n};\n\n\n\n\n\nexport type ApiResource_Bid_TypeDef = ApiBaseResource & {\n _class: \"Bid\",\n\n recipient_id: number,\n auction_id: number,\n\n bidder_number: string,\n bidder_label: string,\n\n amount_cents: number,\n created_at: number,\n placed_at: number,\n\n is_auto: boolean,\n is_overridden: boolean,\n};\n", "/**\n *\n * WARNING: this file should contain *only* compile-time constants. Keep in sync with Rails code and other systems\n *\n */\nimport {\n AuctionBiddingApprovalMode_TypeDef,\n AuctionSegmentType_TypeDef,\n AuctionTimelineState_TypeDef,\n AuctionType_TypeDef,\n BiddingWarrantState_TypeDef, ItemMediaType_TypeDef,\n ObjectWithTypedProperties\n} from \"./type_defs/model\";\nimport {\n AuctionBiddingApprovalModeCode_Enum,\n AuctionSegmentTypeCode_Enum,\n AuctionTimelineStateCode_Enum,\n AuctionTimelineStateCodeID_Enum,\n BiddingWarrantStateCode_Enum, ItemMediaTypeCodeID_Enum\n} from \"./type_defs/api\";\n\n\nconst LotsSorting_Criteria = {\n LotId: {\n id: 0,\n label: 'Lot ID',\n },\n\n LotNumber: {\n id: 1,\n label: 'Number',\n },\n\n LotCustomSort: {\n id: 2,\n label: 'Run Order',\n },\n\n ItemRefno: {\n id: 21,\n label: 'Inventory RefNo',\n },\n\n ItemName: {\n id: 22,\n label: 'Name',\n },\n}\n\n\nconst LotsSorting = {\n Criteria: LotsSorting_Criteria,\n}\n\n\n\n\nconst AuctionTimelineStates_DATA:ObjectWithTypedProperties = {\n upcoming: {\n id: AuctionTimelineStateCodeID_Enum.upcoming,\n code: AuctionTimelineStateCode_Enum.upcoming,\n name: 'Upcoming',\n isUpcoming: true,\n isActive: true,\n },\n running_stalled: {\n id: AuctionTimelineStateCodeID_Enum.running_stalled,\n code: AuctionTimelineStateCode_Enum.running_stalled,\n name: 'Paused',\n isStalled: true,\n isRunning: true,\n isActive: true,\n },\n running_live: {\n id: AuctionTimelineStateCodeID_Enum.running_live,\n code: AuctionTimelineStateCode_Enum.running_live,\n name: 'Running',\n isLive: true,\n isRunning: true,\n isActive: true,\n },\n completed: {\n id: AuctionTimelineStateCodeID_Enum.completed,\n code: AuctionTimelineStateCode_Enum.completed,\n name: 'Completed',\n isCompleted: true,\n },\n}\n\nconst AuctionTimelineStates_mapById:Map = new Map(Object.values(AuctionTimelineStates_DATA).map(v => [v.id, v]));\n\n\nconst AuctionTypeEnum_DATA:ObjectWithTypedProperties = {\n webcast: {\n id: 11,\n label: 'Webcast',\n name: 'Live Webcast',\n isWebcast: true,\n hasWebcastBidding: true,\n },\n timed: {\n id: 20,\n label: 'Timed',\n name: 'Timed Online',\n isTimed: true,\n isOnlineOnly: true,\n hasOnlineBidding: true,\n hasTimedBidding: true,\n },\n combined_prebid_webcast: {\n id: 21,\n label: 'Prebid+Webcast',\n name: 'Combined Prebid & Webcast',\n isCombinedPrebid: true,\n isCombinedAny: true,\n hasWebcastBidding: true,\n hasOnlineBidding: true,\n hasTimedBidding: true,\n },\n sealed: {\n id: 30,\n label: 'Sealed',\n name: 'Sealed Bid',\n isSealed: true,\n isOnlineOnly: true,\n hasOnlineBidding: true,\n hasSecretBidding: true,\n },\n combined_absentee_webcast: {\n id: 31,\n label: 'Absentee+Webcast',\n name: 'Combined Absentee & Webcast',\n isCombinedAbsentee: true,\n isCombinedAny: true,\n hasWebcastBidding: true,\n hasOnlineBidding: true,\n hasSecretBidding: true,\n },\n}\n\nconst AuctionTypeEnum_mapById:Map = new Map(Object.values(AuctionTypeEnum_DATA).map(v => [v.id, v]));\n\nconst AuctionSegmentTypes_DATA:ObjectWithTypedProperties = {\n online: {\n code: AuctionSegmentTypeCode_Enum.online,\n isOnline: true,\n },\n\n webcast: {\n code: AuctionSegmentTypeCode_Enum.webcast,\n isWebcast: true,\n }\n}\nconst AuctionSegmentTypes_mapByCode:Map = new Map(Object.values(AuctionSegmentTypes_DATA).map(v => [v.code, v]));\n\n\n\nconst BiddingWarrantState_DATA:ObjectWithTypedProperties = {\n allowed: {\n code: BiddingWarrantStateCode_Enum.allowed,\n isAllowed: true,\n },\n\n pending: {\n code: BiddingWarrantStateCode_Enum.pending,\n isPendingResponse: true,\n },\n\n declined: {\n code: BiddingWarrantStateCode_Enum.declined,\n isDeclined: true,\n },\n\n must_accept_terms: {\n code: BiddingWarrantStateCode_Enum.must_accept_terms,\n isMustAcceptTerms: true,\n hasRequiredBidderAction: true,\n },\n\n must_request: {\n code: BiddingWarrantStateCode_Enum.must_request,\n isMustRequest: true,\n hasRequiredBidderAction: true,\n },\n\n must_setup_account: {\n code: BiddingWarrantStateCode_Enum.must_setup_account,\n isMustSetupAccount: true,\n hasRequiredBidderAction: true,\n },\n\n must_setup_card: {\n code: BiddingWarrantStateCode_Enum.must_setup_card,\n isMustSetupCard: true,\n hasRequiredBidderAction: true,\n }\n}\n\nconst BiddingWarrantState_mapByCode:Map = new Map(Object.values(BiddingWarrantState_DATA).map((v:BiddingWarrantState_TypeDef) => [v.code, v]))\n\n\n\n\nconst AuctionBiddingApprovalModes_DATA:ObjectWithTypedProperties = {\n manual: {\n code: AuctionBiddingApprovalModeCode_Enum.manual,\n isManual: true,\n },\n\n auto: {\n code: AuctionBiddingApprovalModeCode_Enum.auto_auction,\n isAuto: true,\n }\n}\n\nconst AuctionBiddingApprovalModes_mapByCode:Map =\n new Map(Object.values(AuctionBiddingApprovalModes_DATA).map((v:AuctionBiddingApprovalMode_TypeDef) => [v.code, v]))\n\n\n\n\n\nconst ItemMediaTypes_DATA:ObjectWithTypedProperties = {\n image: {\n code: ItemMediaTypeCodeID_Enum.image,\n isImage: true,\n },\n\n video_youtube: {\n code: ItemMediaTypeCodeID_Enum.video_youtube,\n isVideo: true,\n isVideoYoutube: true,\n },\n\n video_vimeo: {\n code: ItemMediaTypeCodeID_Enum.video_vimeo,\n isVideo: true,\n isVideoVimeo: true,\n },\n}\n\nconst ItemMediaTypes_mapByID:Map =\n new Map(Object.values(ItemMediaTypes_DATA).map((v:ItemMediaType_TypeDef) => [v.code, v]))\n\n\n\n\n\n\nconst ApiParams = {\n DefaultPageSize: 48, // should divide by [2,3,4]; keep in sync with rails api/PagyGrape::DEFAULT_PAGE_SIZE\n}\n\n\nexport enum WebcastScreenTypeCodesEnum {\n clerk= 'clerk',\n auctioneer = 'auctioneer',\n onsite = 'onsite',\n bidder = 'bidder',\n viewer = 'viewer',\n viewer_embedded = 'viewer_embedded'\n}\n\nconst StaticModelsAndConstants = {\n\n LotsSorting: LotsSorting,\n ApiParams: ApiParams,\n\n AuctionTypes: {\n data: AuctionTypeEnum_DATA,\n getById: (id):AuctionType_TypeDef => AuctionTypeEnum_mapById.get(id),\n },\n\n AuctionTimelineStates: {\n data: AuctionTimelineStates_DATA,\n getById: (id):AuctionTimelineState_TypeDef => AuctionTimelineStates_mapById.get(id),\n },\n\n AuctionSegmentTypes: {\n data: AuctionSegmentTypes_DATA,\n getByCode: (code):AuctionSegmentType_TypeDef => AuctionSegmentTypes_mapByCode.get(code),\n },\n\n BiddingWarrantStates: {\n data: BiddingWarrantState_DATA,\n getByCode: (code):BiddingWarrantState_TypeDef => BiddingWarrantState_mapByCode.get(code),\n },\n\n AuctionBiddingApprovalModes: {\n data: AuctionBiddingApprovalModes_DATA,\n getByCode: (code):AuctionBiddingApprovalMode_TypeDef => AuctionBiddingApprovalModes_mapByCode.get(code),\n },\n\n ItemMediaTypes: {\n data: ItemMediaTypes_DATA,\n getById: (id:number):ItemMediaType_TypeDef => ItemMediaTypes_mapByID.get(id)\n },\n}\n\n\n\nexport default StaticModelsAndConstants;\n", "/**\n * @license React\n * react.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n'use strict';var l=Symbol.for(\"react.element\"),n=Symbol.for(\"react.portal\"),p=Symbol.for(\"react.fragment\"),q=Symbol.for(\"react.strict_mode\"),r=Symbol.for(\"react.profiler\"),t=Symbol.for(\"react.provider\"),u=Symbol.for(\"react.context\"),v=Symbol.for(\"react.forward_ref\"),w=Symbol.for(\"react.suspense\"),x=Symbol.for(\"react.memo\"),y=Symbol.for(\"react.lazy\"),z=Symbol.iterator;function A(a){if(null===a||\"object\"!==typeof a)return null;a=z&&a[z]||a[\"@@iterator\"];return\"function\"===typeof a?a:null}\nvar B={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},C=Object.assign,D={};function E(a,b,e){this.props=a;this.context=b;this.refs=D;this.updater=e||B}E.prototype.isReactComponent={};\nE.prototype.setState=function(a,b){if(\"object\"!==typeof a&&\"function\"!==typeof a&&null!=a)throw Error(\"setState(...): takes an object of state variables to update or a function which returns an object of state variables.\");this.updater.enqueueSetState(this,a,b,\"setState\")};E.prototype.forceUpdate=function(a){this.updater.enqueueForceUpdate(this,a,\"forceUpdate\")};function F(){}F.prototype=E.prototype;function G(a,b,e){this.props=a;this.context=b;this.refs=D;this.updater=e||B}var H=G.prototype=new F;\nH.constructor=G;C(H,E.prototype);H.isPureReactComponent=!0;var I=Array.isArray,J=Object.prototype.hasOwnProperty,K={current:null},L={key:!0,ref:!0,__self:!0,__source:!0};\nfunction M(a,b,e){var d,c={},k=null,h=null;if(null!=b)for(d in void 0!==b.ref&&(h=b.ref),void 0!==b.key&&(k=\"\"+b.key),b)J.call(b,d)&&!L.hasOwnProperty(d)&&(c[d]=b[d]);var g=arguments.length-2;if(1===g)c.children=e;else if(1>>1,e=a[d];if(0>>1;dg(C,c))ng(x,C)?(a[d]=x,a[n]=c,d=n):(a[d]=C,a[m]=c,d=m);else if(ng(x,c))a[d]=x,a[n]=c,d=n;else break a}}return b}\nfunction g(a,b){var c=a.sortIndex-b.sortIndex;return 0!==c?c:a.id-b.id}if(\"object\"===typeof performance&&\"function\"===typeof performance.now){var l=performance;exports.unstable_now=function(){return l.now()}}else{var p=Date,q=p.now();exports.unstable_now=function(){return p.now()-q}}var r=[],t=[],u=1,v=null,y=3,z=!1,A=!1,B=!1,D=\"function\"===typeof setTimeout?setTimeout:null,E=\"function\"===typeof clearTimeout?clearTimeout:null,F=\"undefined\"!==typeof setImmediate?setImmediate:null;\n\"undefined\"!==typeof navigator&&void 0!==navigator.scheduling&&void 0!==navigator.scheduling.isInputPending&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function G(a){for(var b=h(t);null!==b;){if(null===b.callback)k(t);else if(b.startTime<=a)k(t),b.sortIndex=b.expirationTime,f(r,b);else break;b=h(t)}}function H(a){B=!1;G(a);if(!A)if(null!==h(r))A=!0,I(J);else{var b=h(t);null!==b&&K(H,b.startTime-a)}}\nfunction J(a,b){A=!1;B&&(B=!1,E(L),L=-1);z=!0;var c=y;try{G(b);for(v=h(r);null!==v&&(!(v.expirationTime>b)||a&&!M());){var d=v.callback;if(\"function\"===typeof d){v.callback=null;y=v.priorityLevel;var e=d(v.expirationTime<=b);b=exports.unstable_now();\"function\"===typeof e?v.callback=e:v===h(r)&&k(r);G(b)}else k(r);v=h(r)}if(null!==v)var w=!0;else{var m=h(t);null!==m&&K(H,m.startTime-b);w=!1}return w}finally{v=null,y=c,z=!1}}var N=!1,O=null,L=-1,P=5,Q=-1;\nfunction M(){return exports.unstable_now()-Qa||125d?(a.sortIndex=c,f(t,a),null===h(r)&&a===h(t)&&(B?(E(L),L=-1):B=!0,K(H,c-d))):(a.sortIndex=e,f(r,a),A||z||(A=!0,I(J)));return a};\nexports.unstable_shouldYield=M;exports.unstable_wrapCallback=function(a){var b=y;return function(){var c=y;y=b;try{return a.apply(this,arguments)}finally{y=c}}};\n", "'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/scheduler.production.min.js');\n} else {\n module.exports = require('./cjs/scheduler.development.js');\n}\n", "/**\n * @license React\n * react-dom.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n/*\n Modernizr 3.0.0pre (Custom Build) | MIT\n*/\n'use strict';var aa=require(\"react\"),ca=require(\"scheduler\");function p(a){for(var b=\"https://reactjs.org/docs/error-decoder.html?invariant=\"+a,c=1;cb}return!1}function v(a,b,c,d,e,f,g){this.acceptsBooleans=2===b||3===b||4===b;this.attributeName=d;this.attributeNamespace=e;this.mustUseProperty=c;this.propertyName=a;this.type=b;this.sanitizeURL=f;this.removeEmptyString=g}var z={};\n\"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style\".split(\" \").forEach(function(a){z[a]=new v(a,0,!1,a,null,!1,!1)});[[\"acceptCharset\",\"accept-charset\"],[\"className\",\"class\"],[\"htmlFor\",\"for\"],[\"httpEquiv\",\"http-equiv\"]].forEach(function(a){var b=a[0];z[b]=new v(b,1,!1,a[1],null,!1,!1)});[\"contentEditable\",\"draggable\",\"spellCheck\",\"value\"].forEach(function(a){z[a]=new v(a,2,!1,a.toLowerCase(),null,!1,!1)});\n[\"autoReverse\",\"externalResourcesRequired\",\"focusable\",\"preserveAlpha\"].forEach(function(a){z[a]=new v(a,2,!1,a,null,!1,!1)});\"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope\".split(\" \").forEach(function(a){z[a]=new v(a,3,!1,a.toLowerCase(),null,!1,!1)});\n[\"checked\",\"multiple\",\"muted\",\"selected\"].forEach(function(a){z[a]=new v(a,3,!0,a,null,!1,!1)});[\"capture\",\"download\"].forEach(function(a){z[a]=new v(a,4,!1,a,null,!1,!1)});[\"cols\",\"rows\",\"size\",\"span\"].forEach(function(a){z[a]=new v(a,6,!1,a,null,!1,!1)});[\"rowSpan\",\"start\"].forEach(function(a){z[a]=new v(a,5,!1,a.toLowerCase(),null,!1,!1)});var ra=/[\\-:]([a-z])/g;function sa(a){return a[1].toUpperCase()}\n\"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height\".split(\" \").forEach(function(a){var b=a.replace(ra,\nsa);z[b]=new v(b,1,!1,a,null,!1,!1)});\"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type\".split(\" \").forEach(function(a){var b=a.replace(ra,sa);z[b]=new v(b,1,!1,a,\"http://www.w3.org/1999/xlink\",!1,!1)});[\"xml:base\",\"xml:lang\",\"xml:space\"].forEach(function(a){var b=a.replace(ra,sa);z[b]=new v(b,1,!1,a,\"http://www.w3.org/XML/1998/namespace\",!1,!1)});[\"tabIndex\",\"crossOrigin\"].forEach(function(a){z[a]=new v(a,1,!1,a.toLowerCase(),null,!1,!1)});\nz.xlinkHref=new v(\"xlinkHref\",1,!1,\"xlink:href\",\"http://www.w3.org/1999/xlink\",!0,!1);[\"src\",\"href\",\"action\",\"formAction\"].forEach(function(a){z[a]=new v(a,1,!1,a.toLowerCase(),null,!0,!0)});\nfunction ta(a,b,c,d){var e=z.hasOwnProperty(b)?z[b]:null;if(null!==e?0!==e.type:d||!(2h||e[g]!==f[h]){var k=\"\\n\"+e[g].replace(\" at new \",\" at \");a.displayName&&k.includes(\"\")&&(k=k.replace(\"\",a.displayName));return k}while(1<=g&&0<=h)}break}}}finally{Na=!1,Error.prepareStackTrace=c}return(a=a?a.displayName||a.name:\"\")?Ma(a):\"\"}\nfunction Pa(a){switch(a.tag){case 5:return Ma(a.type);case 16:return Ma(\"Lazy\");case 13:return Ma(\"Suspense\");case 19:return Ma(\"SuspenseList\");case 0:case 2:case 15:return a=Oa(a.type,!1),a;case 11:return a=Oa(a.type.render,!1),a;case 1:return a=Oa(a.type,!0),a;default:return\"\"}}\nfunction Qa(a){if(null==a)return null;if(\"function\"===typeof a)return a.displayName||a.name||null;if(\"string\"===typeof a)return a;switch(a){case ya:return\"Fragment\";case wa:return\"Portal\";case Aa:return\"Profiler\";case za:return\"StrictMode\";case Ea:return\"Suspense\";case Fa:return\"SuspenseList\"}if(\"object\"===typeof a)switch(a.$$typeof){case Ca:return(a.displayName||\"Context\")+\".Consumer\";case Ba:return(a._context.displayName||\"Context\")+\".Provider\";case Da:var b=a.render;a=a.displayName;a||(a=b.displayName||\nb.name||\"\",a=\"\"!==a?\"ForwardRef(\"+a+\")\":\"ForwardRef\");return a;case Ga:return b=a.displayName||null,null!==b?b:Qa(a.type)||\"Memo\";case Ha:b=a._payload;a=a._init;try{return Qa(a(b))}catch(c){}}return null}\nfunction Ra(a){var b=a.type;switch(a.tag){case 24:return\"Cache\";case 9:return(b.displayName||\"Context\")+\".Consumer\";case 10:return(b._context.displayName||\"Context\")+\".Provider\";case 18:return\"DehydratedFragment\";case 11:return a=b.render,a=a.displayName||a.name||\"\",b.displayName||(\"\"!==a?\"ForwardRef(\"+a+\")\":\"ForwardRef\");case 7:return\"Fragment\";case 5:return b;case 4:return\"Portal\";case 3:return\"Root\";case 6:return\"Text\";case 16:return Qa(b);case 8:return b===za?\"StrictMode\":\"Mode\";case 22:return\"Offscreen\";\ncase 12:return\"Profiler\";case 21:return\"Scope\";case 13:return\"Suspense\";case 19:return\"SuspenseList\";case 25:return\"TracingMarker\";case 1:case 0:case 17:case 2:case 14:case 15:if(\"function\"===typeof b)return b.displayName||b.name||null;if(\"string\"===typeof b)return b}return null}function Sa(a){switch(typeof a){case \"boolean\":case \"number\":case \"string\":case \"undefined\":return a;case \"object\":return a;default:return\"\"}}\nfunction Ta(a){var b=a.type;return(a=a.nodeName)&&\"input\"===a.toLowerCase()&&(\"checkbox\"===b||\"radio\"===b)}\nfunction Ua(a){var b=Ta(a)?\"checked\":\"value\",c=Object.getOwnPropertyDescriptor(a.constructor.prototype,b),d=\"\"+a[b];if(!a.hasOwnProperty(b)&&\"undefined\"!==typeof c&&\"function\"===typeof c.get&&\"function\"===typeof c.set){var e=c.get,f=c.set;Object.defineProperty(a,b,{configurable:!0,get:function(){return e.call(this)},set:function(a){d=\"\"+a;f.call(this,a)}});Object.defineProperty(a,b,{enumerable:c.enumerable});return{getValue:function(){return d},setValue:function(a){d=\"\"+a},stopTracking:function(){a._valueTracker=\nnull;delete a[b]}}}}function Va(a){a._valueTracker||(a._valueTracker=Ua(a))}function Wa(a){if(!a)return!1;var b=a._valueTracker;if(!b)return!0;var c=b.getValue();var d=\"\";a&&(d=Ta(a)?a.checked?\"true\":\"false\":a.value);a=d;return a!==c?(b.setValue(a),!0):!1}function Xa(a){a=a||(\"undefined\"!==typeof document?document:void 0);if(\"undefined\"===typeof a)return null;try{return a.activeElement||a.body}catch(b){return a.body}}\nfunction Ya(a,b){var c=b.checked;return A({},b,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:null!=c?c:a._wrapperState.initialChecked})}function Za(a,b){var c=null==b.defaultValue?\"\":b.defaultValue,d=null!=b.checked?b.checked:b.defaultChecked;c=Sa(null!=b.value?b.value:c);a._wrapperState={initialChecked:d,initialValue:c,controlled:\"checkbox\"===b.type||\"radio\"===b.type?null!=b.checked:null!=b.value}}function ab(a,b){b=b.checked;null!=b&&ta(a,\"checked\",b,!1)}\nfunction bb(a,b){ab(a,b);var c=Sa(b.value),d=b.type;if(null!=c)if(\"number\"===d){if(0===c&&\"\"===a.value||a.value!=c)a.value=\"\"+c}else a.value!==\"\"+c&&(a.value=\"\"+c);else if(\"submit\"===d||\"reset\"===d){a.removeAttribute(\"value\");return}b.hasOwnProperty(\"value\")?cb(a,b.type,c):b.hasOwnProperty(\"defaultValue\")&&cb(a,b.type,Sa(b.defaultValue));null==b.checked&&null!=b.defaultChecked&&(a.defaultChecked=!!b.defaultChecked)}\nfunction db(a,b,c){if(b.hasOwnProperty(\"value\")||b.hasOwnProperty(\"defaultValue\")){var d=b.type;if(!(\"submit\"!==d&&\"reset\"!==d||void 0!==b.value&&null!==b.value))return;b=\"\"+a._wrapperState.initialValue;c||b===a.value||(a.value=b);a.defaultValue=b}c=a.name;\"\"!==c&&(a.name=\"\");a.defaultChecked=!!a._wrapperState.initialChecked;\"\"!==c&&(a.name=c)}\nfunction cb(a,b,c){if(\"number\"!==b||Xa(a.ownerDocument)!==a)null==c?a.defaultValue=\"\"+a._wrapperState.initialValue:a.defaultValue!==\"\"+c&&(a.defaultValue=\"\"+c)}var eb=Array.isArray;\nfunction fb(a,b,c,d){a=a.options;if(b){b={};for(var e=0;e\"+b.valueOf().toString()+\"\";for(b=mb.firstChild;a.firstChild;)a.removeChild(a.firstChild);for(;b.firstChild;)a.appendChild(b.firstChild)}});\nfunction ob(a,b){if(b){var c=a.firstChild;if(c&&c===a.lastChild&&3===c.nodeType){c.nodeValue=b;return}}a.textContent=b}\nvar pb={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,\nzoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},qb=[\"Webkit\",\"ms\",\"Moz\",\"O\"];Object.keys(pb).forEach(function(a){qb.forEach(function(b){b=b+a.charAt(0).toUpperCase()+a.substring(1);pb[b]=pb[a]})});function rb(a,b,c){return null==b||\"boolean\"===typeof b||\"\"===b?\"\":c||\"number\"!==typeof b||0===b||pb.hasOwnProperty(a)&&pb[a]?(\"\"+b).trim():b+\"px\"}\nfunction sb(a,b){a=a.style;for(var c in b)if(b.hasOwnProperty(c)){var d=0===c.indexOf(\"--\"),e=rb(c,b[c],d);\"float\"===c&&(c=\"cssFloat\");d?a.setProperty(c,e):a[c]=e}}var tb=A({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});\nfunction ub(a,b){if(b){if(tb[a]&&(null!=b.children||null!=b.dangerouslySetInnerHTML))throw Error(p(137,a));if(null!=b.dangerouslySetInnerHTML){if(null!=b.children)throw Error(p(60));if(\"object\"!==typeof b.dangerouslySetInnerHTML||!(\"__html\"in b.dangerouslySetInnerHTML))throw Error(p(61));}if(null!=b.style&&\"object\"!==typeof b.style)throw Error(p(62));}}\nfunction vb(a,b){if(-1===a.indexOf(\"-\"))return\"string\"===typeof b.is;switch(a){case \"annotation-xml\":case \"color-profile\":case \"font-face\":case \"font-face-src\":case \"font-face-uri\":case \"font-face-format\":case \"font-face-name\":case \"missing-glyph\":return!1;default:return!0}}var wb=null;function xb(a){a=a.target||a.srcElement||window;a.correspondingUseElement&&(a=a.correspondingUseElement);return 3===a.nodeType?a.parentNode:a}var yb=null,zb=null,Ab=null;\nfunction Bb(a){if(a=Cb(a)){if(\"function\"!==typeof yb)throw Error(p(280));var b=a.stateNode;b&&(b=Db(b),yb(a.stateNode,a.type,b))}}function Eb(a){zb?Ab?Ab.push(a):Ab=[a]:zb=a}function Fb(){if(zb){var a=zb,b=Ab;Ab=zb=null;Bb(a);if(b)for(a=0;a>>=0;return 0===a?32:31-(pc(a)/qc|0)|0}var rc=64,sc=4194304;\nfunction tc(a){switch(a&-a){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return a&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;\ndefault:return a}}function uc(a,b){var c=a.pendingLanes;if(0===c)return 0;var d=0,e=a.suspendedLanes,f=a.pingedLanes,g=c&268435455;if(0!==g){var h=g&~e;0!==h?d=tc(h):(f&=g,0!==f&&(d=tc(f)))}else g=c&~e,0!==g?d=tc(g):0!==f&&(d=tc(f));if(0===d)return 0;if(0!==b&&b!==d&&0===(b&e)&&(e=d&-d,f=b&-b,e>=f||16===e&&0!==(f&4194240)))return b;0!==(d&4)&&(d|=c&16);b=a.entangledLanes;if(0!==b)for(a=a.entanglements,b&=d;0c;c++)b.push(a);return b}\nfunction Ac(a,b,c){a.pendingLanes|=b;536870912!==b&&(a.suspendedLanes=0,a.pingedLanes=0);a=a.eventTimes;b=31-oc(b);a[b]=c}function Bc(a,b){var c=a.pendingLanes&~b;a.pendingLanes=b;a.suspendedLanes=0;a.pingedLanes=0;a.expiredLanes&=b;a.mutableReadLanes&=b;a.entangledLanes&=b;b=a.entanglements;var d=a.eventTimes;for(a=a.expirationTimes;0=be),ee=String.fromCharCode(32),fe=!1;\nfunction ge(a,b){switch(a){case \"keyup\":return-1!==$d.indexOf(b.keyCode);case \"keydown\":return 229!==b.keyCode;case \"keypress\":case \"mousedown\":case \"focusout\":return!0;default:return!1}}function he(a){a=a.detail;return\"object\"===typeof a&&\"data\"in a?a.data:null}var ie=!1;function je(a,b){switch(a){case \"compositionend\":return he(b);case \"keypress\":if(32!==b.which)return null;fe=!0;return ee;case \"textInput\":return a=b.data,a===ee&&fe?null:a;default:return null}}\nfunction ke(a,b){if(ie)return\"compositionend\"===a||!ae&&ge(a,b)?(a=nd(),md=ld=kd=null,ie=!1,a):null;switch(a){case \"paste\":return null;case \"keypress\":if(!(b.ctrlKey||b.altKey||b.metaKey)||b.ctrlKey&&b.altKey){if(b.char&&1=b)return{node:c,offset:b-a};a=d}a:{for(;c;){if(c.nextSibling){c=c.nextSibling;break a}c=c.parentNode}c=void 0}c=Je(c)}}function Le(a,b){return a&&b?a===b?!0:a&&3===a.nodeType?!1:b&&3===b.nodeType?Le(a,b.parentNode):\"contains\"in a?a.contains(b):a.compareDocumentPosition?!!(a.compareDocumentPosition(b)&16):!1:!1}\nfunction Me(){for(var a=window,b=Xa();b instanceof a.HTMLIFrameElement;){try{var c=\"string\"===typeof b.contentWindow.location.href}catch(d){c=!1}if(c)a=b.contentWindow;else break;b=Xa(a.document)}return b}function Ne(a){var b=a&&a.nodeName&&a.nodeName.toLowerCase();return b&&(\"input\"===b&&(\"text\"===a.type||\"search\"===a.type||\"tel\"===a.type||\"url\"===a.type||\"password\"===a.type)||\"textarea\"===b||\"true\"===a.contentEditable)}\nfunction Oe(a){var b=Me(),c=a.focusedElem,d=a.selectionRange;if(b!==c&&c&&c.ownerDocument&&Le(c.ownerDocument.documentElement,c)){if(null!==d&&Ne(c))if(b=d.start,a=d.end,void 0===a&&(a=b),\"selectionStart\"in c)c.selectionStart=b,c.selectionEnd=Math.min(a,c.value.length);else if(a=(b=c.ownerDocument||document)&&b.defaultView||window,a.getSelection){a=a.getSelection();var e=c.textContent.length,f=Math.min(d.start,e);d=void 0===d.end?f:Math.min(d.end,e);!a.extend&&f>d&&(e=d,d=f,f=e);e=Ke(c,f);var g=Ke(c,\nd);e&&g&&(1!==a.rangeCount||a.anchorNode!==e.node||a.anchorOffset!==e.offset||a.focusNode!==g.node||a.focusOffset!==g.offset)&&(b=b.createRange(),b.setStart(e.node,e.offset),a.removeAllRanges(),f>d?(a.addRange(b),a.extend(g.node,g.offset)):(b.setEnd(g.node,g.offset),a.addRange(b)))}b=[];for(a=c;a=a.parentNode;)1===a.nodeType&&b.push({element:a,left:a.scrollLeft,top:a.scrollTop});\"function\"===typeof c.focus&&c.focus();for(c=0;c=document.documentMode,Qe=null,Re=null,Se=null,Te=!1;\nfunction Ue(a,b,c){var d=c.window===c?c.document:9===c.nodeType?c:c.ownerDocument;Te||null==Qe||Qe!==Xa(d)||(d=Qe,\"selectionStart\"in d&&Ne(d)?d={start:d.selectionStart,end:d.selectionEnd}:(d=(d.ownerDocument&&d.ownerDocument.defaultView||window).getSelection(),d={anchorNode:d.anchorNode,anchorOffset:d.anchorOffset,focusNode:d.focusNode,focusOffset:d.focusOffset}),Se&&Ie(Se,d)||(Se=d,d=oe(Re,\"onSelect\"),0Tf||(a.current=Sf[Tf],Sf[Tf]=null,Tf--)}function G(a,b){Tf++;Sf[Tf]=a.current;a.current=b}var Vf={},H=Uf(Vf),Wf=Uf(!1),Xf=Vf;function Yf(a,b){var c=a.type.contextTypes;if(!c)return Vf;var d=a.stateNode;if(d&&d.__reactInternalMemoizedUnmaskedChildContext===b)return d.__reactInternalMemoizedMaskedChildContext;var e={},f;for(f in c)e[f]=b[f];d&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=b,a.__reactInternalMemoizedMaskedChildContext=e);return e}\nfunction Zf(a){a=a.childContextTypes;return null!==a&&void 0!==a}function $f(){E(Wf);E(H)}function ag(a,b,c){if(H.current!==Vf)throw Error(p(168));G(H,b);G(Wf,c)}function bg(a,b,c){var d=a.stateNode;b=b.childContextTypes;if(\"function\"!==typeof d.getChildContext)return c;d=d.getChildContext();for(var e in d)if(!(e in b))throw Error(p(108,Ra(a)||\"Unknown\",e));return A({},c,d)}\nfunction cg(a){a=(a=a.stateNode)&&a.__reactInternalMemoizedMergedChildContext||Vf;Xf=H.current;G(H,a);G(Wf,Wf.current);return!0}function dg(a,b,c){var d=a.stateNode;if(!d)throw Error(p(169));c?(a=bg(a,b,Xf),d.__reactInternalMemoizedMergedChildContext=a,E(Wf),E(H),G(H,a)):E(Wf);G(Wf,c)}var eg=null,fg=!1,gg=!1;function hg(a){null===eg?eg=[a]:eg.push(a)}function ig(a){fg=!0;hg(a)}\nfunction jg(){if(!gg&&null!==eg){gg=!0;var a=0,b=C;try{var c=eg;for(C=1;a>=g;e-=g;rg=1<<32-oc(b)+e|c<w?(x=u,u=null):x=u.sibling;var n=r(e,u,h[w],k);if(null===n){null===u&&(u=x);break}a&&u&&null===n.alternate&&b(e,u);g=f(n,g,w);null===m?l=n:m.sibling=n;m=n;u=x}if(w===h.length)return c(e,u),I&&tg(e,w),l;if(null===u){for(;ww?(x=m,m=null):x=m.sibling;var t=r(e,m,n.value,k);if(null===t){null===m&&(m=x);break}a&&m&&null===t.alternate&&b(e,m);g=f(t,g,w);null===u?l=t:u.sibling=t;u=t;m=x}if(n.done)return c(e,\nm),I&&tg(e,w),l;if(null===m){for(;!n.done;w++,n=h.next())n=q(e,n.value,k),null!==n&&(g=f(n,g,w),null===u?l=n:u.sibling=n,u=n);I&&tg(e,w);return l}for(m=d(e,m);!n.done;w++,n=h.next())n=y(m,e,w,n.value,k),null!==n&&(a&&null!==n.alternate&&m.delete(null===n.key?w:n.key),g=f(n,g,w),null===u?l=n:u.sibling=n,u=n);a&&m.forEach(function(a){return b(e,a)});I&&tg(e,w);return l}function J(a,d,f,h){\"object\"===typeof f&&null!==f&&f.type===ya&&null===f.key&&(f=f.props.children);if(\"object\"===typeof f&&null!==f){switch(f.$$typeof){case va:a:{for(var k=\nf.key,l=d;null!==l;){if(l.key===k){k=f.type;if(k===ya){if(7===l.tag){c(a,l.sibling);d=e(l,f.props.children);d.return=a;a=d;break a}}else if(l.elementType===k||\"object\"===typeof k&&null!==k&&k.$$typeof===Ha&&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 batch = newBatch; // Supply a getter just to skip dealing with ESM bindings\n\nexport const getBatch = () => batch;", "import * as React from 'react';\nconst ContextKey = Symbol.for(`react-redux-context`);\nconst gT = typeof globalThis !== \"undefined\" ? globalThis :\n/* fall back to a per-module scope (pre-8.1 behaviour) if `globalThis` is not available */\n{};\n\nfunction getContext() {\n var _gT$ContextKey;\n\n if (!React.createContext) return {};\n const contextMap = (_gT$ContextKey = gT[ContextKey]) != null ? _gT$ContextKey : gT[ContextKey] = new Map();\n let realContext = contextMap.get(React.createContext);\n\n if (!realContext) {\n realContext = React.createContext(null);\n\n if (process.env.NODE_ENV !== 'production') {\n realContext.displayName = 'ReactRedux';\n }\n\n contextMap.set(React.createContext, realContext);\n }\n\n return realContext;\n}\n\nexport const ReactReduxContext = /*#__PURE__*/getContext();\nexport default ReactReduxContext;", "import { useContext } from 'react';\nimport { ReactReduxContext } from '../components/Context';\n\n/**\r\n * Hook factory, which creates a `useReduxContext` hook bound to a given context. This is a low-level\r\n * hook that you should usually not need to call directly.\r\n *\r\n * @param {React.Context} [context=ReactReduxContext] Context passed to your ``.\r\n * @returns {Function} A `useReduxContext` hook bound to the specified context.\r\n */\nexport function createReduxContextHook(context = ReactReduxContext) {\n return function useReduxContext() {\n const contextValue = useContext(context);\n\n if (process.env.NODE_ENV !== 'production' && !contextValue) {\n throw new Error('could not find react-redux context value; please ensure the component is wrapped in a ');\n }\n\n return contextValue;\n };\n}\n/**\r\n * A hook to access the value of the `ReactReduxContext`. This is a low-level\r\n * hook that you should usually not need to call directly.\r\n *\r\n * @returns {any} the value of the `ReactReduxContext`\r\n *\r\n * @example\r\n *\r\n * import React from 'react'\r\n * import { useReduxContext } from 'react-redux'\r\n *\r\n * export const CounterComponent = () => {\r\n * const { store } = useReduxContext()\r\n * return
{store.getState()}
\r\n * }\r\n */\n\nexport const useReduxContext = /*#__PURE__*/createReduxContextHook();", "export const notInitialized = () => {\n throw new Error('uSES not initialized!');\n};", "import { useCallback, useDebugValue, useRef } from 'react';\nimport { createReduxContextHook, useReduxContext as useDefaultReduxContext } from './useReduxContext';\nimport { ReactReduxContext } from '../components/Context';\nimport { notInitialized } from '../utils/useSyncExternalStore';\nlet useSyncExternalStoreWithSelector = notInitialized;\nexport const initializeUseSelector = fn => {\n useSyncExternalStoreWithSelector = fn;\n};\n\nconst refEquality = (a, b) => a === b;\n/**\r\n * Hook factory, which creates a `useSelector` hook bound to a given context.\r\n *\r\n * @param {React.Context} [context=ReactReduxContext] Context passed to your ``.\r\n * @returns {Function} A `useSelector` hook bound to the specified context.\r\n */\n\n\nexport function createSelectorHook(context = ReactReduxContext) {\n const useReduxContext = context === ReactReduxContext ? useDefaultReduxContext : createReduxContextHook(context);\n return function useSelector(selector, equalityFnOrOptions = {}) {\n const {\n equalityFn = refEquality,\n stabilityCheck = undefined,\n noopCheck = undefined\n } = typeof equalityFnOrOptions === 'function' ? {\n equalityFn: equalityFnOrOptions\n } : equalityFnOrOptions;\n\n if (process.env.NODE_ENV !== 'production') {\n if (!selector) {\n throw new Error(`You must pass a selector to useSelector`);\n }\n\n if (typeof selector !== 'function') {\n throw new Error(`You must pass a function as a selector to useSelector`);\n }\n\n if (typeof equalityFn !== 'function') {\n throw new Error(`You must pass a function as an equality function to useSelector`);\n }\n }\n\n const {\n store,\n subscription,\n getServerState,\n stabilityCheck: globalStabilityCheck,\n noopCheck: globalNoopCheck\n } = useReduxContext();\n const firstRun = useRef(true);\n const wrappedSelector = useCallback({\n [selector.name](state) {\n const selected = selector(state);\n\n if (process.env.NODE_ENV !== 'production') {\n const finalStabilityCheck = typeof stabilityCheck === 'undefined' ? globalStabilityCheck : stabilityCheck;\n\n if (finalStabilityCheck === 'always' || finalStabilityCheck === 'once' && firstRun.current) {\n const toCompare = selector(state);\n\n if (!equalityFn(selected, toCompare)) {\n let stack = undefined;\n\n try {\n throw new Error();\n } catch (e) {\n ;\n ({\n stack\n } = e);\n }\n\n console.warn('Selector ' + (selector.name || 'unknown') + ' returned a different result when called with the same parameters. This can lead to unnecessary rerenders.' + '\\nSelectors that return a new reference (such as an object or an array) should be memoized: https://redux.js.org/usage/deriving-data-selectors#optimizing-selectors-with-memoization', {\n state,\n selected,\n selected2: toCompare,\n stack\n });\n }\n }\n\n const finalNoopCheck = typeof noopCheck === 'undefined' ? globalNoopCheck : noopCheck;\n\n if (finalNoopCheck === 'always' || finalNoopCheck === 'once' && firstRun.current) {\n // @ts-ignore\n if (selected === state) {\n let stack = undefined;\n\n try {\n throw new Error();\n } catch (e) {\n ;\n ({\n stack\n } = e);\n }\n\n console.warn('Selector ' + (selector.name || 'unknown') + ' returned the root state when called. This can lead to unnecessary rerenders.' + '\\nSelectors that return the entire state are almost certainly a mistake, as they will cause a rerender whenever *anything* in state changes.', {\n stack\n });\n }\n }\n\n if (firstRun.current) firstRun.current = false;\n }\n\n return selected;\n }\n\n }[selector.name], [selector, globalStabilityCheck, stabilityCheck]);\n const selectedState = useSyncExternalStoreWithSelector(subscription.addNestedSub, store.getState, getServerState || store.getState, wrappedSelector, equalityFn);\n useDebugValue(selectedState);\n return selectedState;\n };\n}\n/**\r\n * A hook to access the redux store's state. This hook takes a selector function\r\n * as an argument. The selector is called with the store state.\r\n *\r\n * This hook takes an optional equality comparison function as the second parameter\r\n * that allows you to customize the way the selected state is compared to determine\r\n * whether the component needs to be re-rendered.\r\n *\r\n * @param {Function} selector the selector function\r\n * @param {Function=} equalityFn the function that will be used to determine equality\r\n *\r\n * @returns {any} the selected state\r\n *\r\n * @example\r\n *\r\n * import React from 'react'\r\n * import { useSelector } from 'react-redux'\r\n *\r\n * export const CounterComponent = () => {\r\n * const counter = useSelector(state => state.counter)\r\n * return
{counter}
\r\n * }\r\n */\n\nexport const useSelector = /*#__PURE__*/createSelectorHook();", "function _extends() {\n return _extends = Object.assign ? Object.assign.bind() : function (n) {\n for (var e = 1; e < arguments.length; e++) {\n var t = arguments[e];\n for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);\n }\n return n;\n }, _extends.apply(null, arguments);\n}\nexport { _extends as default };", "function _objectWithoutPropertiesLoose(r, e) {\n if (null == r) return {};\n var t = {};\n for (var n in r) if ({}.hasOwnProperty.call(r, n)) {\n if (e.includes(n)) continue;\n t[n] = r[n];\n }\n return t;\n}\nexport { _objectWithoutPropertiesLoose as default };", "/** @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", "'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", "/**\n * @license React\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'use strict';var b=Symbol.for(\"react.element\"),c=Symbol.for(\"react.portal\"),d=Symbol.for(\"react.fragment\"),e=Symbol.for(\"react.strict_mode\"),f=Symbol.for(\"react.profiler\"),g=Symbol.for(\"react.provider\"),h=Symbol.for(\"react.context\"),k=Symbol.for(\"react.server_context\"),l=Symbol.for(\"react.forward_ref\"),m=Symbol.for(\"react.suspense\"),n=Symbol.for(\"react.suspense_list\"),p=Symbol.for(\"react.memo\"),q=Symbol.for(\"react.lazy\"),t=Symbol.for(\"react.offscreen\"),u;u=Symbol.for(\"react.module.reference\");\nfunction v(a){if(\"object\"===typeof a&&null!==a){var r=a.$$typeof;switch(r){case b:switch(a=a.type,a){case d:case f:case e:case m:case n:return a;default:switch(a=a&&a.$$typeof,a){case k:case h:case l:case q:case p:case g:return a;default:return r}}case c:return r}}}exports.ContextConsumer=h;exports.ContextProvider=g;exports.Element=b;exports.ForwardRef=l;exports.Fragment=d;exports.Lazy=q;exports.Memo=p;exports.Portal=c;exports.Profiler=f;exports.StrictMode=e;exports.Suspense=m;\nexports.SuspenseList=n;exports.isAsyncMode=function(){return!1};exports.isConcurrentMode=function(){return!1};exports.isContextConsumer=function(a){return v(a)===h};exports.isContextProvider=function(a){return v(a)===g};exports.isElement=function(a){return\"object\"===typeof a&&null!==a&&a.$$typeof===b};exports.isForwardRef=function(a){return v(a)===l};exports.isFragment=function(a){return v(a)===d};exports.isLazy=function(a){return v(a)===q};exports.isMemo=function(a){return v(a)===p};\nexports.isPortal=function(a){return v(a)===c};exports.isProfiler=function(a){return v(a)===f};exports.isStrictMode=function(a){return v(a)===e};exports.isSuspense=function(a){return v(a)===m};exports.isSuspenseList=function(a){return v(a)===n};\nexports.isValidElementType=function(a){return\"string\"===typeof a||\"function\"===typeof a||a===d||a===f||a===e||a===m||a===n||a===t||\"object\"===typeof a&&null!==a&&(a.$$typeof===q||a.$$typeof===p||a.$$typeof===g||a.$$typeof===h||a.$$typeof===l||a.$$typeof===u||void 0!==a.getModuleId)?!0:!1};exports.typeOf=v;\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", "/**\r\n * Prints a warning in the console if it exists.\r\n *\r\n * @param {String} message The warning message.\r\n * @returns {void}\r\n */\nexport default function warning(message) {\n /* eslint-disable no-console */\n if (typeof console !== 'undefined' && typeof console.error === 'function') {\n console.error(message);\n }\n /* eslint-enable no-console */\n\n\n try {\n // This error was thrown as a convenience so that if you enable\n // \"break on all exceptions\" in your console,\n // it would pause the execution at this line.\n throw new Error(message);\n /* eslint-disable no-empty */\n } catch (e) {}\n /* eslint-enable no-empty */\n\n}", "import warning from '../utils/warning';\n\nfunction verify(selector, methodName) {\n if (!selector) {\n throw new Error(`Unexpected value for ${methodName} in connect.`);\n } else if (methodName === 'mapStateToProps' || methodName === 'mapDispatchToProps') {\n if (!Object.prototype.hasOwnProperty.call(selector, 'dependsOnOwnProps')) {\n warning(`The selector for ${methodName} of connect did not specify a value for dependsOnOwnProps.`);\n }\n }\n}\n\nexport default function verifySubselectors(mapStateToProps, mapDispatchToProps, mergeProps) {\n verify(mapStateToProps, 'mapStateToProps');\n verify(mapDispatchToProps, 'mapDispatchToProps');\n verify(mergeProps, 'mergeProps');\n}", "import _objectWithoutPropertiesLoose from \"@babel/runtime/helpers/esm/objectWithoutPropertiesLoose\";\nconst _excluded = [\"initMapStateToProps\", \"initMapDispatchToProps\", \"initMergeProps\"];\nimport verifySubselectors from './verifySubselectors';\nexport function pureFinalPropsSelectorFactory(mapStateToProps, mapDispatchToProps, mergeProps, dispatch, {\n areStatesEqual,\n areOwnPropsEqual,\n areStatePropsEqual\n}) {\n let hasRunAtLeastOnce = false;\n let state;\n let ownProps;\n let stateProps;\n let dispatchProps;\n let mergedProps;\n\n function handleFirstCall(firstState, firstOwnProps) {\n state = firstState;\n ownProps = firstOwnProps;\n stateProps = mapStateToProps(state, ownProps);\n dispatchProps = mapDispatchToProps(dispatch, ownProps);\n mergedProps = mergeProps(stateProps, dispatchProps, ownProps);\n hasRunAtLeastOnce = true;\n return mergedProps;\n }\n\n function handleNewPropsAndNewState() {\n stateProps = mapStateToProps(state, ownProps);\n if (mapDispatchToProps.dependsOnOwnProps) dispatchProps = mapDispatchToProps(dispatch, ownProps);\n mergedProps = mergeProps(stateProps, dispatchProps, ownProps);\n return mergedProps;\n }\n\n function handleNewProps() {\n if (mapStateToProps.dependsOnOwnProps) stateProps = mapStateToProps(state, ownProps);\n if (mapDispatchToProps.dependsOnOwnProps) dispatchProps = mapDispatchToProps(dispatch, ownProps);\n mergedProps = mergeProps(stateProps, dispatchProps, ownProps);\n return mergedProps;\n }\n\n function handleNewState() {\n const nextStateProps = mapStateToProps(state, ownProps);\n const statePropsChanged = !areStatePropsEqual(nextStateProps, stateProps);\n stateProps = nextStateProps;\n if (statePropsChanged) mergedProps = mergeProps(stateProps, dispatchProps, ownProps);\n return mergedProps;\n }\n\n function handleSubsequentCalls(nextState, nextOwnProps) {\n const propsChanged = !areOwnPropsEqual(nextOwnProps, ownProps);\n const stateChanged = !areStatesEqual(nextState, state, nextOwnProps, ownProps);\n state = nextState;\n ownProps = nextOwnProps;\n if (propsChanged && stateChanged) return handleNewPropsAndNewState();\n if (propsChanged) return handleNewProps();\n if (stateChanged) return handleNewState();\n return mergedProps;\n }\n\n return function pureFinalPropsSelector(nextState, nextOwnProps) {\n return hasRunAtLeastOnce ? handleSubsequentCalls(nextState, nextOwnProps) : handleFirstCall(nextState, nextOwnProps);\n };\n}\n// TODO: Add more comments\n// The selector returned by selectorFactory will memoize its results,\n// allowing connect's shouldComponentUpdate to return false if final\n// props have not changed.\nexport default function finalPropsSelectorFactory(dispatch, _ref) {\n let {\n initMapStateToProps,\n initMapDispatchToProps,\n initMergeProps\n } = _ref,\n options = _objectWithoutPropertiesLoose(_ref, _excluded);\n\n const mapStateToProps = initMapStateToProps(dispatch, options);\n const mapDispatchToProps = initMapDispatchToProps(dispatch, options);\n const mergeProps = initMergeProps(dispatch, options);\n\n if (process.env.NODE_ENV !== 'production') {\n verifySubselectors(mapStateToProps, mapDispatchToProps, mergeProps);\n }\n\n return pureFinalPropsSelectorFactory(mapStateToProps, mapDispatchToProps, mergeProps, dispatch, options);\n}", "export default function bindActionCreators(actionCreators, dispatch) {\n const boundActionCreators = {};\n\n for (const key in actionCreators) {\n const actionCreator = actionCreators[key];\n\n if (typeof actionCreator === 'function') {\n boundActionCreators[key] = (...args) => dispatch(actionCreator(...args));\n }\n }\n\n return boundActionCreators;\n}", "/**\r\n * @param {any} obj The object to inspect.\r\n * @returns {boolean} True if the argument appears to be a plain object.\r\n */\nexport default function isPlainObject(obj) {\n if (typeof obj !== 'object' || obj === null) return false;\n let proto = Object.getPrototypeOf(obj);\n if (proto === null) return true;\n let baseProto = proto;\n\n while (Object.getPrototypeOf(baseProto) !== null) {\n baseProto = Object.getPrototypeOf(baseProto);\n }\n\n return proto === baseProto;\n}", "import isPlainObject from './isPlainObject';\nimport warning from './warning';\nexport default function verifyPlainObject(value, displayName, methodName) {\n if (!isPlainObject(value)) {\n warning(`${methodName}() in ${displayName} must return a plain object. Instead received ${value}.`);\n }\n}", "import verifyPlainObject from '../utils/verifyPlainObject';\nexport function wrapMapToPropsConstant( // * Note:\n// It seems that the dispatch argument\n// could be a dispatch function in some cases (ex: whenMapDispatchToPropsIsMissing)\n// and a state object in some others (ex: whenMapStateToPropsIsMissing)\n// eslint-disable-next-line no-unused-vars\ngetConstant) {\n return function initConstantSelector(dispatch) {\n const constant = getConstant(dispatch);\n\n function constantSelector() {\n return constant;\n }\n\n constantSelector.dependsOnOwnProps = false;\n return constantSelector;\n };\n} // dependsOnOwnProps is used by createMapToPropsProxy to determine whether to pass props as args\n// to the mapToProps function being wrapped. It is also used by makePurePropsSelector to determine\n// whether mapToProps needs to be invoked when props have changed.\n//\n// A length of one signals that mapToProps does not depend on props from the parent component.\n// A length of zero is assumed to mean mapToProps is getting args via arguments or ...args and\n// therefore not reporting its length accurately..\n// TODO Can this get pulled out so that we can subscribe directly to the store if we don't need ownProps?\n\nexport function getDependsOnOwnProps(mapToProps) {\n return mapToProps.dependsOnOwnProps ? Boolean(mapToProps.dependsOnOwnProps) : mapToProps.length !== 1;\n} // Used by whenMapStateToPropsIsFunction and whenMapDispatchToPropsIsFunction,\n// this function wraps mapToProps in a proxy function which does several things:\n//\n// * Detects whether the mapToProps function being called depends on props, which\n// is used by selectorFactory to decide if it should reinvoke on props changes.\n//\n// * On first call, handles mapToProps if returns another function, and treats that\n// new function as the true mapToProps for subsequent calls.\n//\n// * On first call, verifies the first result is a plain object, in order to warn\n// the developer that their mapToProps function is not returning a valid result.\n//\n\nexport function wrapMapToPropsFunc(mapToProps, methodName) {\n return function initProxySelector(dispatch, {\n displayName\n }) {\n const proxy = function mapToPropsProxy(stateOrDispatch, ownProps) {\n return proxy.dependsOnOwnProps ? proxy.mapToProps(stateOrDispatch, ownProps) : proxy.mapToProps(stateOrDispatch, undefined);\n }; // allow detectFactoryAndVerify to get ownProps\n\n\n proxy.dependsOnOwnProps = true;\n\n proxy.mapToProps = function detectFactoryAndVerify(stateOrDispatch, ownProps) {\n proxy.mapToProps = mapToProps;\n proxy.dependsOnOwnProps = getDependsOnOwnProps(mapToProps);\n let props = proxy(stateOrDispatch, ownProps);\n\n if (typeof props === 'function') {\n proxy.mapToProps = props;\n proxy.dependsOnOwnProps = getDependsOnOwnProps(props);\n props = proxy(stateOrDispatch, ownProps);\n }\n\n if (process.env.NODE_ENV !== 'production') verifyPlainObject(props, displayName, methodName);\n return props;\n };\n\n return proxy;\n };\n}", "export function createInvalidArgFactory(arg, name) {\n return (dispatch, options) => {\n throw new Error(`Invalid value of type ${typeof arg} for ${name} argument when connecting component ${options.wrappedComponentName}.`);\n };\n}", "import bindActionCreators from '../utils/bindActionCreators';\nimport { wrapMapToPropsConstant, wrapMapToPropsFunc } from './wrapMapToProps';\nimport { createInvalidArgFactory } from './invalidArgFactory';\nexport function mapDispatchToPropsFactory(mapDispatchToProps) {\n return mapDispatchToProps && typeof mapDispatchToProps === 'object' ? wrapMapToPropsConstant(dispatch => // @ts-ignore\n bindActionCreators(mapDispatchToProps, dispatch)) : !mapDispatchToProps ? wrapMapToPropsConstant(dispatch => ({\n dispatch\n })) : typeof mapDispatchToProps === 'function' ? // @ts-ignore\n wrapMapToPropsFunc(mapDispatchToProps, 'mapDispatchToProps') : createInvalidArgFactory(mapDispatchToProps, 'mapDispatchToProps');\n}", "import { wrapMapToPropsConstant, wrapMapToPropsFunc } from './wrapMapToProps';\nimport { createInvalidArgFactory } from './invalidArgFactory';\nexport function mapStateToPropsFactory(mapStateToProps) {\n return !mapStateToProps ? wrapMapToPropsConstant(() => ({})) : typeof mapStateToProps === 'function' ? // @ts-ignore\n wrapMapToPropsFunc(mapStateToProps, 'mapStateToProps') : createInvalidArgFactory(mapStateToProps, 'mapStateToProps');\n}", "import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport verifyPlainObject from '../utils/verifyPlainObject';\nimport { createInvalidArgFactory } from './invalidArgFactory';\nexport function defaultMergeProps(stateProps, dispatchProps, ownProps) {\n // @ts-ignore\n return _extends({}, ownProps, stateProps, dispatchProps);\n}\nexport function wrapMergePropsFunc(mergeProps) {\n return function initMergePropsProxy(dispatch, {\n displayName,\n areMergedPropsEqual\n }) {\n let hasRunOnce = false;\n let mergedProps;\n return function mergePropsProxy(stateProps, dispatchProps, ownProps) {\n const nextMergedProps = mergeProps(stateProps, dispatchProps, ownProps);\n\n if (hasRunOnce) {\n if (!areMergedPropsEqual(nextMergedProps, mergedProps)) mergedProps = nextMergedProps;\n } else {\n hasRunOnce = true;\n mergedProps = nextMergedProps;\n if (process.env.NODE_ENV !== 'production') verifyPlainObject(mergedProps, displayName, 'mergeProps');\n }\n\n return mergedProps;\n };\n };\n}\nexport function mergePropsFactory(mergeProps) {\n return !mergeProps ? () => defaultMergeProps : typeof mergeProps === 'function' ? wrapMergePropsFunc(mergeProps) : createInvalidArgFactory(mergeProps, 'mergeProps');\n}", "import { getBatch } from './batch'; // encapsulates the subscription logic for connecting a component to the redux store, as\n// well as nesting subscriptions of descendant components, so that we can ensure the\n// ancestor components re-render before descendants\n\nfunction createListenerCollection() {\n const batch = getBatch();\n let first = null;\n let last = null;\n return {\n clear() {\n first = null;\n last = null;\n },\n\n notify() {\n batch(() => {\n let listener = first;\n\n while (listener) {\n listener.callback();\n listener = listener.next;\n }\n });\n },\n\n get() {\n let listeners = [];\n let listener = first;\n\n while (listener) {\n listeners.push(listener);\n listener = listener.next;\n }\n\n return listeners;\n },\n\n subscribe(callback) {\n let isSubscribed = true;\n let listener = last = {\n callback,\n next: null,\n prev: last\n };\n\n if (listener.prev) {\n listener.prev.next = listener;\n } else {\n first = listener;\n }\n\n return function unsubscribe() {\n if (!isSubscribed || first === null) return;\n isSubscribed = false;\n\n if (listener.next) {\n listener.next.prev = listener.prev;\n } else {\n last = listener.prev;\n }\n\n if (listener.prev) {\n listener.prev.next = listener.next;\n } else {\n first = listener.next;\n }\n };\n }\n\n };\n}\n\nconst nullListeners = {\n notify() {},\n\n get: () => []\n};\nexport function createSubscription(store, parentSub) {\n let unsubscribe;\n let listeners = nullListeners; // Reasons to keep the subscription active\n\n let subscriptionsAmount = 0; // Is this specific subscription subscribed (or only nested ones?)\n\n let selfSubscribed = false;\n\n function addNestedSub(listener) {\n trySubscribe();\n const cleanupListener = listeners.subscribe(listener); // cleanup nested sub\n\n let removed = false;\n return () => {\n if (!removed) {\n removed = true;\n cleanupListener();\n tryUnsubscribe();\n }\n };\n }\n\n function notifyNestedSubs() {\n listeners.notify();\n }\n\n function handleChangeWrapper() {\n if (subscription.onStateChange) {\n subscription.onStateChange();\n }\n }\n\n function isSubscribed() {\n return selfSubscribed;\n }\n\n function trySubscribe() {\n subscriptionsAmount++;\n\n if (!unsubscribe) {\n unsubscribe = parentSub ? parentSub.addNestedSub(handleChangeWrapper) : store.subscribe(handleChangeWrapper);\n listeners = createListenerCollection();\n }\n }\n\n function tryUnsubscribe() {\n subscriptionsAmount--;\n\n if (unsubscribe && subscriptionsAmount === 0) {\n unsubscribe();\n unsubscribe = undefined;\n listeners.clear();\n listeners = nullListeners;\n }\n }\n\n function trySubscribeSelf() {\n if (!selfSubscribed) {\n selfSubscribed = true;\n trySubscribe();\n }\n }\n\n function tryUnsubscribeSelf() {\n if (selfSubscribed) {\n selfSubscribed = false;\n tryUnsubscribe();\n }\n }\n\n const subscription = {\n addNestedSub,\n notifyNestedSubs,\n handleChangeWrapper,\n isSubscribed,\n trySubscribe: trySubscribeSelf,\n tryUnsubscribe: tryUnsubscribeSelf,\n getListeners: () => listeners\n };\n return subscription;\n}", "import * as React from 'react'; // React currently throws a warning when using useLayoutEffect on the server.\n// To get around it, we can conditionally useEffect on the server (no-op) and\n// useLayoutEffect in the browser. We need useLayoutEffect to ensure the store\n// subscription callback always has the selector from the latest render commit\n// available, otherwise a store update may happen between render and the effect,\n// which may cause missed updates; we also must ensure the store subscription\n// is created synchronously, otherwise a store update may occur before the\n// subscription is created and an inconsistent state may be observed\n// Matches logic in React's `shared/ExecutionEnvironment` file\n\nexport const canUseDOM = !!(typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined');\nexport const useIsomorphicLayoutEffect = canUseDOM ? React.useLayoutEffect : React.useEffect;", "function is(x, y) {\n if (x === y) {\n return x !== 0 || y !== 0 || 1 / x === 1 / y;\n } else {\n return x !== x && y !== y;\n }\n}\n\nexport default function shallowEqual(objA, objB) {\n if (is(objA, objB)) return true;\n\n if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {\n return false;\n }\n\n const keysA = Object.keys(objA);\n const keysB = Object.keys(objB);\n if (keysA.length !== keysB.length) return false;\n\n for (let i = 0; i < keysA.length; i++) {\n if (!Object.prototype.hasOwnProperty.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) {\n return false;\n }\n }\n\n return true;\n}", "import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutPropertiesLoose from \"@babel/runtime/helpers/esm/objectWithoutPropertiesLoose\";\nconst _excluded = [\"reactReduxForwardedRef\"];\n\n/* eslint-disable valid-jsdoc, @typescript-eslint/no-unused-vars */\nimport hoistStatics from 'hoist-non-react-statics';\nimport * as React from 'react';\nimport { isValidElementType, isContextConsumer } from 'react-is';\nimport defaultSelectorFactory from '../connect/selectorFactory';\nimport { mapDispatchToPropsFactory } from '../connect/mapDispatchToProps';\nimport { mapStateToPropsFactory } from '../connect/mapStateToProps';\nimport { mergePropsFactory } from '../connect/mergeProps';\nimport { createSubscription } from '../utils/Subscription';\nimport { useIsomorphicLayoutEffect } from '../utils/useIsomorphicLayoutEffect';\nimport shallowEqual from '../utils/shallowEqual';\nimport warning from '../utils/warning';\nimport { ReactReduxContext } from './Context';\nimport { notInitialized } from '../utils/useSyncExternalStore';\nlet useSyncExternalStore = notInitialized;\nexport const initializeConnect = fn => {\n useSyncExternalStore = fn;\n}; // Define some constant arrays just to avoid re-creating these\n\nconst EMPTY_ARRAY = [null, 0];\nconst NO_SUBSCRIPTION_ARRAY = [null, null]; // Attempts to stringify whatever not-really-a-component value we were given\n// for logging in an error message\n\nconst stringifyComponent = Comp => {\n try {\n return JSON.stringify(Comp);\n } catch (err) {\n return String(Comp);\n }\n};\n\n// This is \"just\" a `useLayoutEffect`, but with two modifications:\n// - we need to fall back to `useEffect` in SSR to avoid annoying warnings\n// - we extract this to a separate function to avoid closing over values\n// and causing memory leaks\nfunction useIsomorphicLayoutEffectWithArgs(effectFunc, effectArgs, dependencies) {\n useIsomorphicLayoutEffect(() => effectFunc(...effectArgs), dependencies);\n} // Effect callback, extracted: assign the latest props values to refs for later usage\n\n\nfunction captureWrapperProps(lastWrapperProps, lastChildProps, renderIsScheduled, wrapperProps, // actualChildProps: unknown,\nchildPropsFromStoreUpdate, notifyNestedSubs) {\n // We want to capture the wrapper props and child props we used for later comparisons\n lastWrapperProps.current = wrapperProps;\n renderIsScheduled.current = false; // If the render was from a store update, clear out that reference and cascade the subscriber update\n\n if (childPropsFromStoreUpdate.current) {\n childPropsFromStoreUpdate.current = null;\n notifyNestedSubs();\n }\n} // Effect callback, extracted: subscribe to the Redux store or nearest connected ancestor,\n// check for updates after dispatched actions, and trigger re-renders.\n\n\nfunction subscribeUpdates(shouldHandleStateChanges, store, subscription, childPropsSelector, lastWrapperProps, lastChildProps, renderIsScheduled, isMounted, childPropsFromStoreUpdate, notifyNestedSubs, // forceComponentUpdateDispatch: React.Dispatch,\nadditionalSubscribeListener) {\n // If we're not subscribed to the store, nothing to do here\n if (!shouldHandleStateChanges) return () => {}; // Capture values for checking if and when this component unmounts\n\n let didUnsubscribe = false;\n let lastThrownError = null; // We'll run this callback every time a store subscription update propagates to this component\n\n const checkForUpdates = () => {\n if (didUnsubscribe || !isMounted.current) {\n // Don't run stale listeners.\n // Redux doesn't guarantee unsubscriptions happen until next dispatch.\n return;\n } // TODO We're currently calling getState ourselves here, rather than letting `uSES` do it\n\n\n const latestStoreState = store.getState();\n let newChildProps, error;\n\n try {\n // Actually run the selector with the most recent store state and wrapper props\n // to determine what the child props should be\n newChildProps = childPropsSelector(latestStoreState, lastWrapperProps.current);\n } catch (e) {\n error = e;\n lastThrownError = e;\n }\n\n if (!error) {\n lastThrownError = null;\n } // If the child props haven't changed, nothing to do here - cascade the subscription update\n\n\n if (newChildProps === lastChildProps.current) {\n if (!renderIsScheduled.current) {\n notifyNestedSubs();\n }\n } else {\n // Save references to the new child props. Note that we track the \"child props from store update\"\n // as a ref instead of a useState/useReducer because we need a way to determine if that value has\n // been processed. If this went into useState/useReducer, we couldn't clear out the value without\n // forcing another re-render, which we don't want.\n lastChildProps.current = newChildProps;\n childPropsFromStoreUpdate.current = newChildProps;\n renderIsScheduled.current = true; // TODO This is hacky and not how `uSES` is meant to be used\n // Trigger the React `useSyncExternalStore` subscriber\n\n additionalSubscribeListener();\n }\n }; // Actually subscribe to the nearest connected ancestor (or store)\n\n\n subscription.onStateChange = checkForUpdates;\n subscription.trySubscribe(); // Pull data from the store after first render in case the store has\n // changed since we began.\n\n checkForUpdates();\n\n const unsubscribeWrapper = () => {\n didUnsubscribe = true;\n subscription.tryUnsubscribe();\n subscription.onStateChange = null;\n\n if (lastThrownError) {\n // It's possible that we caught an error due to a bad mapState function, but the\n // parent re-rendered without this component and we're about to unmount.\n // This shouldn't happen as long as we do top-down subscriptions correctly, but\n // if we ever do those wrong, this throw will surface the error in our tests.\n // In that case, throw the error from here so it doesn't get lost.\n throw lastThrownError;\n }\n };\n\n return unsubscribeWrapper;\n} // Reducer initial state creation for our update reducer\n\n\nconst initStateUpdates = () => EMPTY_ARRAY;\n\nfunction strictEqual(a, b) {\n return a === b;\n}\n/**\r\n * Infers the type of props that a connector will inject into a component.\r\n */\n\n\nlet hasWarnedAboutDeprecatedPureOption = false;\n/**\r\n * Connects a React component to a Redux store.\r\n *\r\n * - Without arguments, just wraps the component, without changing the behavior / props\r\n *\r\n * - If 2 params are passed (3rd param, mergeProps, is skipped), default behavior\r\n * is to override ownProps (as stated in the docs), so what remains is everything that's\r\n * not a state or dispatch prop\r\n *\r\n * - When 3rd param is passed, we don't know if ownProps propagate and whether they\r\n * should be valid component props, because it depends on mergeProps implementation.\r\n * As such, it is the user's responsibility to extend ownProps interface from state or\r\n * dispatch props or both when applicable\r\n *\r\n * @param mapStateToProps A function that extracts values from state\r\n * @param mapDispatchToProps Setup for dispatching actions\r\n * @param mergeProps Optional callback to merge state and dispatch props together\r\n * @param options Options for configuring the connection\r\n *\r\n */\n\nfunction connect(mapStateToProps, mapDispatchToProps, mergeProps, {\n // The `pure` option has been removed, so TS doesn't like us destructuring this to check its existence.\n // @ts-ignore\n pure,\n areStatesEqual = strictEqual,\n areOwnPropsEqual = shallowEqual,\n areStatePropsEqual = shallowEqual,\n areMergedPropsEqual = shallowEqual,\n // use React's forwardRef to expose a ref of the wrapped component\n forwardRef = false,\n // the context consumer to use\n context = ReactReduxContext\n} = {}) {\n if (process.env.NODE_ENV !== 'production') {\n if (pure !== undefined && !hasWarnedAboutDeprecatedPureOption) {\n hasWarnedAboutDeprecatedPureOption = true;\n warning('The `pure` option has been removed. `connect` is now always a \"pure/memoized\" component');\n }\n }\n\n const Context = context;\n const initMapStateToProps = mapStateToPropsFactory(mapStateToProps);\n const initMapDispatchToProps = mapDispatchToPropsFactory(mapDispatchToProps);\n const initMergeProps = mergePropsFactory(mergeProps);\n const shouldHandleStateChanges = Boolean(mapStateToProps);\n\n const wrapWithConnect = WrappedComponent => {\n if (process.env.NODE_ENV !== 'production' && !isValidElementType(WrappedComponent)) {\n throw new Error(`You must pass a component to the function returned by connect. Instead received ${stringifyComponent(WrappedComponent)}`);\n }\n\n const wrappedComponentName = WrappedComponent.displayName || WrappedComponent.name || 'Component';\n const displayName = `Connect(${wrappedComponentName})`;\n const selectorFactoryOptions = {\n shouldHandleStateChanges,\n displayName,\n wrappedComponentName,\n WrappedComponent,\n // @ts-ignore\n initMapStateToProps,\n // @ts-ignore\n initMapDispatchToProps,\n initMergeProps,\n areStatesEqual,\n areStatePropsEqual,\n areOwnPropsEqual,\n areMergedPropsEqual\n };\n\n function ConnectFunction(props) {\n const [propsContext, reactReduxForwardedRef, wrapperProps] = React.useMemo(() => {\n // Distinguish between actual \"data\" props that were passed to the wrapper component,\n // and values needed to control behavior (forwarded refs, alternate context instances).\n // To maintain the wrapperProps object reference, memoize this destructuring.\n const {\n reactReduxForwardedRef\n } = props,\n wrapperProps = _objectWithoutPropertiesLoose(props, _excluded);\n\n return [props.context, reactReduxForwardedRef, wrapperProps];\n }, [props]);\n const ContextToUse = React.useMemo(() => {\n // Users may optionally pass in a custom context instance to use instead of our ReactReduxContext.\n // Memoize the check that determines which context instance we should use.\n return propsContext && propsContext.Consumer && // @ts-ignore\n isContextConsumer( /*#__PURE__*/React.createElement(propsContext.Consumer, null)) ? propsContext : Context;\n }, [propsContext, Context]); // Retrieve the store and ancestor subscription via context, if available\n\n const contextValue = React.useContext(ContextToUse); // The store _must_ exist as either a prop or in context.\n // We'll check to see if it _looks_ like a Redux store first.\n // This allows us to pass through a `store` prop that is just a plain value.\n\n const didStoreComeFromProps = Boolean(props.store) && Boolean(props.store.getState) && Boolean(props.store.dispatch);\n const didStoreComeFromContext = Boolean(contextValue) && Boolean(contextValue.store);\n\n if (process.env.NODE_ENV !== 'production' && !didStoreComeFromProps && !didStoreComeFromContext) {\n throw new Error(`Could not find \"store\" in the context of ` + `\"${displayName}\". Either wrap the root component in a , ` + `or pass a custom React context provider to and the corresponding ` + `React context consumer to ${displayName} in connect options.`);\n } // Based on the previous check, one of these must be true\n\n\n const store = didStoreComeFromProps ? props.store : contextValue.store;\n const getServerState = didStoreComeFromContext ? contextValue.getServerState : store.getState;\n const childPropsSelector = React.useMemo(() => {\n // The child props selector needs the store reference as an input.\n // Re-create this selector whenever the store changes.\n return defaultSelectorFactory(store.dispatch, selectorFactoryOptions);\n }, [store]);\n const [subscription, notifyNestedSubs] = React.useMemo(() => {\n if (!shouldHandleStateChanges) return NO_SUBSCRIPTION_ARRAY; // This Subscription's source should match where store came from: props vs. context. A component\n // connected to the store via props shouldn't use subscription from context, or vice versa.\n\n const subscription = createSubscription(store, didStoreComeFromProps ? undefined : contextValue.subscription); // `notifyNestedSubs` is duplicated to handle the case where the component is unmounted in\n // the middle of the notification loop, where `subscription` will then be null. This can\n // probably be avoided if Subscription's listeners logic is changed to not call listeners\n // that have been unsubscribed in the middle of the notification loop.\n\n const notifyNestedSubs = subscription.notifyNestedSubs.bind(subscription);\n return [subscription, notifyNestedSubs];\n }, [store, didStoreComeFromProps, contextValue]); // Determine what {store, subscription} value should be put into nested context, if necessary,\n // and memoize that value to avoid unnecessary context updates.\n\n const overriddenContextValue = React.useMemo(() => {\n if (didStoreComeFromProps) {\n // This component is directly subscribed to a store from props.\n // We don't want descendants reading from this store - pass down whatever\n // the existing context value is from the nearest connected ancestor.\n return contextValue;\n } // Otherwise, put this component's subscription instance into context, so that\n // connected descendants won't update until after this component is done\n\n\n return _extends({}, contextValue, {\n subscription\n });\n }, [didStoreComeFromProps, contextValue, subscription]); // Set up refs to coordinate values between the subscription effect and the render logic\n\n const lastChildProps = React.useRef();\n const lastWrapperProps = React.useRef(wrapperProps);\n const childPropsFromStoreUpdate = React.useRef();\n const renderIsScheduled = React.useRef(false);\n const isProcessingDispatch = React.useRef(false);\n const isMounted = React.useRef(false);\n const latestSubscriptionCallbackError = React.useRef();\n useIsomorphicLayoutEffect(() => {\n isMounted.current = true;\n return () => {\n isMounted.current = false;\n };\n }, []);\n const actualChildPropsSelector = React.useMemo(() => {\n const selector = () => {\n // Tricky logic here:\n // - This render may have been triggered by a Redux store update that produced new child props\n // - However, we may have gotten new wrapper props after that\n // If we have new child props, and the same wrapper props, we know we should use the new child props as-is.\n // But, if we have new wrapper props, those might change the child props, so we have to recalculate things.\n // So, we'll use the child props from store update only if the wrapper props are the same as last time.\n if (childPropsFromStoreUpdate.current && wrapperProps === lastWrapperProps.current) {\n return childPropsFromStoreUpdate.current;\n } // TODO We're reading the store directly in render() here. Bad idea?\n // This will likely cause Bad Things (TM) to happen in Concurrent Mode.\n // Note that we do this because on renders _not_ caused by store updates, we need the latest store state\n // to determine what the child props should be.\n\n\n return childPropsSelector(store.getState(), wrapperProps);\n };\n\n return selector;\n }, [store, wrapperProps]); // We need this to execute synchronously every time we re-render. However, React warns\n // about useLayoutEffect in SSR, so we try to detect environment and fall back to\n // just useEffect instead to avoid the warning, since neither will run anyway.\n\n const subscribeForReact = React.useMemo(() => {\n const subscribe = reactListener => {\n if (!subscription) {\n return () => {};\n }\n\n return subscribeUpdates(shouldHandleStateChanges, store, subscription, // @ts-ignore\n childPropsSelector, lastWrapperProps, lastChildProps, renderIsScheduled, isMounted, childPropsFromStoreUpdate, notifyNestedSubs, reactListener);\n };\n\n return subscribe;\n }, [subscription]);\n useIsomorphicLayoutEffectWithArgs(captureWrapperProps, [lastWrapperProps, lastChildProps, renderIsScheduled, wrapperProps, childPropsFromStoreUpdate, notifyNestedSubs]);\n let actualChildProps;\n\n try {\n actualChildProps = useSyncExternalStore( // TODO We're passing through a big wrapper that does a bunch of extra side effects besides subscribing\n subscribeForReact, // TODO This is incredibly hacky. We've already processed the store update and calculated new child props,\n // TODO and we're just passing that through so it triggers a re-render for us rather than relying on `uSES`.\n actualChildPropsSelector, getServerState ? () => childPropsSelector(getServerState(), wrapperProps) : actualChildPropsSelector);\n } catch (err) {\n if (latestSubscriptionCallbackError.current) {\n ;\n err.message += `\\nThe error may be correlated with this previous error:\\n${latestSubscriptionCallbackError.current.stack}\\n\\n`;\n }\n\n throw err;\n }\n\n useIsomorphicLayoutEffect(() => {\n latestSubscriptionCallbackError.current = undefined;\n childPropsFromStoreUpdate.current = undefined;\n lastChildProps.current = actualChildProps;\n }); // Now that all that's done, we can finally try to actually render the child component.\n // We memoize the elements for the rendered child component as an optimization.\n\n const renderedWrappedComponent = React.useMemo(() => {\n return (\n /*#__PURE__*/\n // @ts-ignore\n React.createElement(WrappedComponent, _extends({}, actualChildProps, {\n ref: reactReduxForwardedRef\n }))\n );\n }, [reactReduxForwardedRef, WrappedComponent, actualChildProps]); // If React sees the exact same element reference as last time, it bails out of re-rendering\n // that child, same as if it was wrapped in React.memo() or returned false from shouldComponentUpdate.\n\n const renderedChild = React.useMemo(() => {\n if (shouldHandleStateChanges) {\n // If this component is subscribed to store updates, we need to pass its own\n // subscription instance down to our descendants. That means rendering the same\n // Context instance, and putting a different value into the context.\n return /*#__PURE__*/React.createElement(ContextToUse.Provider, {\n value: overriddenContextValue\n }, renderedWrappedComponent);\n }\n\n return renderedWrappedComponent;\n }, [ContextToUse, renderedWrappedComponent, overriddenContextValue]);\n return renderedChild;\n }\n\n const _Connect = React.memo(ConnectFunction);\n\n // Add a hacky cast to get the right output type\n const Connect = _Connect;\n Connect.WrappedComponent = WrappedComponent;\n Connect.displayName = ConnectFunction.displayName = displayName;\n\n if (forwardRef) {\n const _forwarded = React.forwardRef(function forwardConnectRef(props, ref) {\n // @ts-ignore\n return /*#__PURE__*/React.createElement(Connect, _extends({}, props, {\n reactReduxForwardedRef: ref\n }));\n });\n\n const forwarded = _forwarded;\n forwarded.displayName = displayName;\n forwarded.WrappedComponent = WrappedComponent;\n return hoistStatics(forwarded, WrappedComponent);\n }\n\n return hoistStatics(Connect, WrappedComponent);\n };\n\n return wrapWithConnect;\n}\n\nexport default connect;", "import * as React from 'react';\nimport { ReactReduxContext } from './Context';\nimport { createSubscription } from '../utils/Subscription';\nimport { useIsomorphicLayoutEffect } from '../utils/useIsomorphicLayoutEffect';\n\nfunction Provider({\n store,\n context,\n children,\n serverState,\n stabilityCheck = 'once',\n noopCheck = 'once'\n}) {\n const contextValue = React.useMemo(() => {\n const subscription = createSubscription(store);\n return {\n store,\n subscription,\n getServerState: serverState ? () => serverState : undefined,\n stabilityCheck,\n noopCheck\n };\n }, [store, serverState, stabilityCheck, noopCheck]);\n const previousState = React.useMemo(() => store.getState(), [store]);\n useIsomorphicLayoutEffect(() => {\n const {\n subscription\n } = contextValue;\n subscription.onStateChange = subscription.notifyNestedSubs;\n subscription.trySubscribe();\n\n if (previousState !== store.getState()) {\n subscription.notifyNestedSubs();\n }\n\n return () => {\n subscription.tryUnsubscribe();\n subscription.onStateChange = undefined;\n };\n }, [contextValue, previousState]);\n const Context = context || ReactReduxContext; // @ts-ignore 'AnyAction' is assignable to the constraint of type 'A', but 'A' could be instantiated with a different subtype\n\n return /*#__PURE__*/React.createElement(Context.Provider, {\n value: contextValue\n }, children);\n}\n\nexport default Provider;", "import { ReactReduxContext } from '../components/Context';\nimport { useReduxContext as useDefaultReduxContext, createReduxContextHook } from './useReduxContext';\n/**\r\n * Hook factory, which creates a `useStore` hook bound to a given context.\r\n *\r\n * @param {React.Context} [context=ReactReduxContext] Context passed to your ``.\r\n * @returns {Function} A `useStore` hook bound to the specified context.\r\n */\n\nexport function createStoreHook(context = ReactReduxContext) {\n const useReduxContext = // @ts-ignore\n context === ReactReduxContext ? useDefaultReduxContext : // @ts-ignore\n createReduxContextHook(context);\n return function useStore() {\n const {\n store\n } = useReduxContext(); // @ts-ignore\n\n return store;\n };\n}\n/**\r\n * A hook to access the redux store.\r\n *\r\n * @returns {any} the redux store\r\n *\r\n * @example\r\n *\r\n * import React from 'react'\r\n * import { useStore } from 'react-redux'\r\n *\r\n * export const ExampleComponent = () => {\r\n * const store = useStore()\r\n * return
{store.getState()}
\r\n * }\r\n */\n\nexport const useStore = /*#__PURE__*/createStoreHook();", "import { ReactReduxContext } from '../components/Context';\nimport { useStore as useDefaultStore, createStoreHook } from './useStore';\n/**\r\n * Hook factory, which creates a `useDispatch` hook bound to a given context.\r\n *\r\n * @param {React.Context} [context=ReactReduxContext] Context passed to your ``.\r\n * @returns {Function} A `useDispatch` hook bound to the specified context.\r\n */\n\nexport function createDispatchHook(context = ReactReduxContext) {\n const useStore = // @ts-ignore\n context === ReactReduxContext ? useDefaultStore : createStoreHook(context);\n return function useDispatch() {\n const store = useStore(); // @ts-ignore\n\n return store.dispatch;\n };\n}\n/**\r\n * A hook to access the redux `dispatch` function.\r\n *\r\n * @returns {any|function} redux store's `dispatch` function\r\n *\r\n * @example\r\n *\r\n * import React, { useCallback } from 'react'\r\n * import { useDispatch } from 'react-redux'\r\n *\r\n * export const CounterComponent = ({ value }) => {\r\n * const dispatch = useDispatch()\r\n * const increaseCounter = useCallback(() => dispatch({ type: 'increase-counter' }), [])\r\n * return (\r\n *
\r\n * {value}\r\n * \r\n *
\r\n * )\r\n * }\r\n */\n\nexport const useDispatch = /*#__PURE__*/createDispatchHook();", "export {};", "import Provider from './components/Provider';\nimport connect from './components/connect';\nimport { ReactReduxContext } from './components/Context';\nimport { useDispatch, createDispatchHook } from './hooks/useDispatch';\nimport { useSelector, createSelectorHook } from './hooks/useSelector';\nimport { useStore, createStoreHook } from './hooks/useStore';\nimport shallowEqual from './utils/shallowEqual';\nexport * from './types';\nexport { Provider, ReactReduxContext, connect, useDispatch, createDispatchHook, useSelector, createSelectorHook, useStore, createStoreHook, shallowEqual };", "// The primary entry point assumes we're working with standard ReactDOM/RN, but\n// older versions that do not include `useSyncExternalStore` (React 16.9 - 17.x).\n// Because of that, the useSyncExternalStore compat shim is needed.\nimport { useSyncExternalStore } from 'use-sync-external-store/shim';\nimport { useSyncExternalStoreWithSelector } from 'use-sync-external-store/shim/with-selector';\nimport { unstable_batchedUpdates as batch } from './utils/reactBatchedUpdates';\nimport { setBatch } from './utils/batch';\nimport { initializeUseSelector } from './hooks/useSelector';\nimport { initializeConnect } from './components/connect';\ninitializeUseSelector(useSyncExternalStoreWithSelector);\ninitializeConnect(useSyncExternalStore); // Enable batched updates in our subscriptions for use\n// with standard React renderers (ReactDOM, React Native)\n\nsetBatch(batch);\nexport { batch };\nexport * from './exports';", "/**\n * @license React\n * react-jsx-runtime.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n'use strict';var f=require(\"react\"),k=Symbol.for(\"react.element\"),l=Symbol.for(\"react.fragment\"),m=Object.prototype.hasOwnProperty,n=f.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,p={key:!0,ref:!0,__self:!0,__source:!0};\nfunction q(c,a,g){var b,d={},e=null,h=null;void 0!==g&&(e=\"\"+g);void 0!==a.key&&(e=\"\"+a.key);void 0!==a.ref&&(h=a.ref);for(b in a)m.call(a,b)&&!p.hasOwnProperty(b)&&(d[b]=a[b]);if(c&&c.defaultProps)for(b in a=c.defaultProps,a)void 0===d[b]&&(d[b]=a[b]);return{$$typeof:k,type:c,key:e,ref:h,props:d,_owner:n.current}}exports.Fragment=l;exports.jsx=q;exports.jsxs=q;\n", "'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/react-jsx-runtime.production.min.js');\n} else {\n module.exports = require('./cjs/react-jsx-runtime.development.js');\n}\n", "import React from \"react\";\nimport {Participant} from \"@nextlot/core/webcast/data/data_types_definitions\";\n\n\ntype ParticipantsType = {\n mapByUserId?: Map,\n onlineBidders: Array,\n offlineBidders: Array,\n onlineViewers: Array,\n offlineViewers: Array,\n};\n\ntype RootCmpPropsType = {\n participants: ParticipantsType,\n\n openChatRoom: (roomId:number)=>void,\n};\n\n\nexport default class ClerkBiddersListTabContentCmp extends React.Component }> {\n\n\n constructor(props) {\n super(props);\n\n this.state = {\n filteredBidders: []\n };\n }\n\n\n handleClick_ParticipantChat = (participant: Participant) => (evt) => {\n this.props.openChatRoom(participant.userId);\n };\n\n handleOnChange = (event) => {\n const participants: ParticipantsType = this.props.participants;\n const allBidders = participants.onlineBidders.concat(participants.offlineBidders);\n const filteredBidders = allBidders.map(bidder => bidder).filter(b => b.bidderNo.startsWith(event.target.value));\n\n if (event.target.value.length === 0) {\n this.setState({\n filteredBidders: []\n });\n }\n\n if (event.target.value.length > 0) {\n if (filteredBidders.length === 0) {\n this.setState({\n filteredBidders: null\n });\n } else {\n this.setState({\n filteredBidders: filteredBidders\n });\n }\n }\n };\n\n\n _renderParticipantsList(participantsList, online) {\n if (participantsList && participantsList.length) {\n return participantsList.map((p) => {\n return (\n
\n
\n
{p.bidderNo}{p.bidderLabel ? ` / ${p.bidderLabel}` : ''}
\n
\n \n \n \n alert('TODO: ban participant: ' + p.userId)}>\n \n \n
\n
\n )\n })\n } else {\n return null;\n }\n }\n\n\n render() {\n const participants: ParticipantsType = this.props.participants;\n\n const sortedOnlineBidders = participants.onlineBidders\n .map(onlineBidder => onlineBidder)\n .sort((a, b) => parseInt(a.bidderNo) < parseInt(b.bidderNo) ? -1 : 1);\n const sortedOfflineBidders = participants.offlineBidders\n .map(offlineBidder => offlineBidder)\n .sort((a, b) => parseInt(a.bidderNo) < parseInt(b.bidderNo) ? -1 : 1);\n const sortedOnlineViewers = participants.onlineViewers\n .map(onlineViewer => onlineViewer)\n .sort((a, b) => parseInt(a.bidderNo) > parseInt(b.bidderNo) ? -1 : 1);\n const sortedOfflineViewers = participants.offlineViewers\n .map(offlineViewer => offlineViewer)\n .sort((a, b) => parseInt(a.bidderNo) > parseInt(b.bidderNo) ? -1 : 1);\n const sortedFilteredBidders = this.state.filteredBidders && this.state.filteredBidders\n .map(bidder => bidder)\n .sort((a, b) => parseInt(a.bidderNo) < parseInt(b.bidderNo) ? -1 : 1);\n\n\n if (participants.onlineBidders) {\n return (\n
\n
\n Search bidder by #\n \n
\n {this.state.filteredBidders\n ? (
\n\n
\n\n
\n Bidders (online: {participants.onlineBidders.length} /\n total: {participants.onlineBidders.length + participants.offlineBidders.length})\n
\n\n {this.state.filteredBidders.length > 0\n ?\n this._renderParticipantsList(sortedFilteredBidders, true)\n :\n (
\n {this._renderParticipantsList(sortedOnlineBidders, true)}\n
\n {this._renderParticipantsList(sortedOfflineBidders, false)}\n
)\n }\n\n
\n Viewers (online: {participants.onlineViewers.length} /\n total: {participants.onlineViewers.length + participants.offlineViewers.length})\n
\n\n {this._renderParticipantsList(sortedOnlineViewers, true)}\n\n
\n\n {this._renderParticipantsList(sortedOfflineViewers, false)}\n
\n\n
\n\n )\n :

No bidder found.

\n }\n
\n )\n } else {\n return null;\n }\n }\n}\n", "// these aren't really private, but nor are they really useful to document\n\n/**\n * @private\n */\nclass LuxonError extends Error {}\n\n/**\n * @private\n */\nexport class InvalidDateTimeError extends LuxonError {\n constructor(reason) {\n super(`Invalid DateTime: ${reason.toMessage()}`);\n }\n}\n\n/**\n * @private\n */\nexport class InvalidIntervalError extends LuxonError {\n constructor(reason) {\n super(`Invalid Interval: ${reason.toMessage()}`);\n }\n}\n\n/**\n * @private\n */\nexport class InvalidDurationError extends LuxonError {\n constructor(reason) {\n super(`Invalid Duration: ${reason.toMessage()}`);\n }\n}\n\n/**\n * @private\n */\nexport class ConflictingSpecificationError extends LuxonError {}\n\n/**\n * @private\n */\nexport class InvalidUnitError extends LuxonError {\n constructor(unit) {\n super(`Invalid unit ${unit}`);\n }\n}\n\n/**\n * @private\n */\nexport class InvalidArgumentError extends LuxonError {}\n\n/**\n * @private\n */\nexport class ZoneIsAbstractError extends LuxonError {\n constructor() {\n super(\"Zone is an abstract class\");\n }\n}\n", "/**\n * @private\n */\n\nconst n = \"numeric\",\n s = \"short\",\n l = \"long\";\n\nexport const DATE_SHORT = {\n year: n,\n month: n,\n day: n,\n};\n\nexport const DATE_MED = {\n year: n,\n month: s,\n day: n,\n};\n\nexport const DATE_MED_WITH_WEEKDAY = {\n year: n,\n month: s,\n day: n,\n weekday: s,\n};\n\nexport const DATE_FULL = {\n year: n,\n month: l,\n day: n,\n};\n\nexport const DATE_HUGE = {\n year: n,\n month: l,\n day: n,\n weekday: l,\n};\n\nexport const TIME_SIMPLE = {\n hour: n,\n minute: n,\n};\n\nexport const TIME_WITH_SECONDS = {\n hour: n,\n minute: n,\n second: n,\n};\n\nexport const TIME_WITH_SHORT_OFFSET = {\n hour: n,\n minute: n,\n second: n,\n timeZoneName: s,\n};\n\nexport const TIME_WITH_LONG_OFFSET = {\n hour: n,\n minute: n,\n second: n,\n timeZoneName: l,\n};\n\nexport const TIME_24_SIMPLE = {\n hour: n,\n minute: n,\n hourCycle: \"h23\",\n};\n\nexport const TIME_24_WITH_SECONDS = {\n hour: n,\n minute: n,\n second: n,\n hourCycle: \"h23\",\n};\n\nexport const TIME_24_WITH_SHORT_OFFSET = {\n hour: n,\n minute: n,\n second: n,\n hourCycle: \"h23\",\n timeZoneName: s,\n};\n\nexport const TIME_24_WITH_LONG_OFFSET = {\n hour: n,\n minute: n,\n second: n,\n hourCycle: \"h23\",\n timeZoneName: l,\n};\n\nexport const DATETIME_SHORT = {\n year: n,\n month: n,\n day: n,\n hour: n,\n minute: n,\n};\n\nexport const DATETIME_SHORT_WITH_SECONDS = {\n year: n,\n month: n,\n day: n,\n hour: n,\n minute: n,\n second: n,\n};\n\nexport const DATETIME_MED = {\n year: n,\n month: s,\n day: n,\n hour: n,\n minute: n,\n};\n\nexport const DATETIME_MED_WITH_SECONDS = {\n year: n,\n month: s,\n day: n,\n hour: n,\n minute: n,\n second: n,\n};\n\nexport const DATETIME_MED_WITH_WEEKDAY = {\n year: n,\n month: s,\n day: n,\n weekday: s,\n hour: n,\n minute: n,\n};\n\nexport const DATETIME_FULL = {\n year: n,\n month: l,\n day: n,\n hour: n,\n minute: n,\n timeZoneName: s,\n};\n\nexport const DATETIME_FULL_WITH_SECONDS = {\n year: n,\n month: l,\n day: n,\n hour: n,\n minute: n,\n second: n,\n timeZoneName: s,\n};\n\nexport const DATETIME_HUGE = {\n year: n,\n month: l,\n day: n,\n weekday: l,\n hour: n,\n minute: n,\n timeZoneName: l,\n};\n\nexport const DATETIME_HUGE_WITH_SECONDS = {\n year: n,\n month: l,\n day: n,\n weekday: l,\n hour: n,\n minute: n,\n second: n,\n timeZoneName: l,\n};\n", "import { ZoneIsAbstractError } from \"./errors.js\";\n\n/**\n * @interface\n */\nexport default class Zone {\n /**\n * The type of zone\n * @abstract\n * @type {string}\n */\n get type() {\n throw new ZoneIsAbstractError();\n }\n\n /**\n * The name of this zone.\n * @abstract\n * @type {string}\n */\n get name() {\n throw new ZoneIsAbstractError();\n }\n\n /**\n * The IANA name of this zone.\n * Defaults to `name` if not overwritten by a subclass.\n * @abstract\n * @type {string}\n */\n get ianaName() {\n return this.name;\n }\n\n /**\n * Returns whether the offset is known to be fixed for the whole year.\n * @abstract\n * @type {boolean}\n */\n get isUniversal() {\n throw new ZoneIsAbstractError();\n }\n\n /**\n * Returns the offset's common name (such as EST) at the specified timestamp\n * @abstract\n * @param {number} ts - Epoch milliseconds for which to get the name\n * @param {Object} opts - Options to affect the format\n * @param {string} opts.format - What style of offset to return. Accepts 'long' or 'short'.\n * @param {string} opts.locale - What locale to return the offset name in.\n * @return {string}\n */\n offsetName(ts, opts) {\n throw new ZoneIsAbstractError();\n }\n\n /**\n * Returns the offset's value as a string\n * @abstract\n * @param {number} ts - Epoch milliseconds for which to get the offset\n * @param {string} format - What style of offset to return.\n * Accepts 'narrow', 'short', or 'techie'. Returning '+6', '+06:00', or '+0600' respectively\n * @return {string}\n */\n formatOffset(ts, format) {\n throw new ZoneIsAbstractError();\n }\n\n /**\n * Return the offset in minutes for this zone at the specified timestamp.\n * @abstract\n * @param {number} ts - Epoch milliseconds for which to compute the offset\n * @return {number}\n */\n offset(ts) {\n throw new ZoneIsAbstractError();\n }\n\n /**\n * Return whether this Zone is equal to another zone\n * @abstract\n * @param {Zone} otherZone - the zone to compare\n * @return {boolean}\n */\n equals(otherZone) {\n throw new ZoneIsAbstractError();\n }\n\n /**\n * Return whether this Zone is valid.\n * @abstract\n * @type {boolean}\n */\n get isValid() {\n throw new ZoneIsAbstractError();\n }\n}\n", "import { formatOffset, parseZoneInfo } from \"../impl/util.js\";\nimport Zone from \"../zone.js\";\n\nlet singleton = null;\n\n/**\n * Represents the local zone for this JavaScript environment.\n * @implements {Zone}\n */\nexport default class SystemZone extends Zone {\n /**\n * Get a singleton instance of the local zone\n * @return {SystemZone}\n */\n static get instance() {\n if (singleton === null) {\n singleton = new SystemZone();\n }\n return singleton;\n }\n\n /** @override **/\n get type() {\n return \"system\";\n }\n\n /** @override **/\n get name() {\n return new Intl.DateTimeFormat().resolvedOptions().timeZone;\n }\n\n /** @override **/\n get isUniversal() {\n return false;\n }\n\n /** @override **/\n offsetName(ts, { format, locale }) {\n return parseZoneInfo(ts, format, locale);\n }\n\n /** @override **/\n formatOffset(ts, format) {\n return formatOffset(this.offset(ts), format);\n }\n\n /** @override **/\n offset(ts) {\n return -new Date(ts).getTimezoneOffset();\n }\n\n /** @override **/\n equals(otherZone) {\n return otherZone.type === \"system\";\n }\n\n /** @override **/\n get isValid() {\n return true;\n }\n}\n", "import { formatOffset, parseZoneInfo, isUndefined, objToLocalTS } from \"../impl/util.js\";\nimport Zone from \"../zone.js\";\n\nlet dtfCache = {};\nfunction makeDTF(zone) {\n if (!dtfCache[zone]) {\n dtfCache[zone] = new Intl.DateTimeFormat(\"en-US\", {\n hour12: false,\n timeZone: zone,\n year: \"numeric\",\n month: \"2-digit\",\n day: \"2-digit\",\n hour: \"2-digit\",\n minute: \"2-digit\",\n second: \"2-digit\",\n era: \"short\",\n });\n }\n return dtfCache[zone];\n}\n\nconst typeToPos = {\n year: 0,\n month: 1,\n day: 2,\n era: 3,\n hour: 4,\n minute: 5,\n second: 6,\n};\n\nfunction hackyOffset(dtf, date) {\n const formatted = dtf.format(date).replace(/\\u200E/g, \"\"),\n parsed = /(\\d+)\\/(\\d+)\\/(\\d+) (AD|BC),? (\\d+):(\\d+):(\\d+)/.exec(formatted),\n [, fMonth, fDay, fYear, fadOrBc, fHour, fMinute, fSecond] = parsed;\n return [fYear, fMonth, fDay, fadOrBc, fHour, fMinute, fSecond];\n}\n\nfunction partsOffset(dtf, date) {\n const formatted = dtf.formatToParts(date);\n const filled = [];\n for (let i = 0; i < formatted.length; i++) {\n const { type, value } = formatted[i];\n const pos = typeToPos[type];\n\n if (type === \"era\") {\n filled[pos] = value;\n } else if (!isUndefined(pos)) {\n filled[pos] = parseInt(value, 10);\n }\n }\n return filled;\n}\n\nlet ianaZoneCache = {};\n/**\n * A zone identified by an IANA identifier, like America/New_York\n * @implements {Zone}\n */\nexport default class IANAZone extends Zone {\n /**\n * @param {string} name - Zone name\n * @return {IANAZone}\n */\n static create(name) {\n if (!ianaZoneCache[name]) {\n ianaZoneCache[name] = new IANAZone(name);\n }\n return ianaZoneCache[name];\n }\n\n /**\n * Reset local caches. Should only be necessary in testing scenarios.\n * @return {void}\n */\n static resetCache() {\n ianaZoneCache = {};\n dtfCache = {};\n }\n\n /**\n * Returns whether the provided string is a valid specifier. This only checks the string's format, not that the specifier identifies a known zone; see isValidZone for that.\n * @param {string} s - The string to check validity on\n * @example IANAZone.isValidSpecifier(\"America/New_York\") //=> true\n * @example IANAZone.isValidSpecifier(\"Sport~~blorp\") //=> false\n * @deprecated For backward compatibility, this forwards to isValidZone, better use `isValidZone()` directly instead.\n * @return {boolean}\n */\n static isValidSpecifier(s) {\n return this.isValidZone(s);\n }\n\n /**\n * Returns whether the provided string identifies a real zone\n * @param {string} zone - The string to check\n * @example IANAZone.isValidZone(\"America/New_York\") //=> true\n * @example IANAZone.isValidZone(\"Fantasia/Castle\") //=> false\n * @example IANAZone.isValidZone(\"Sport~~blorp\") //=> false\n * @return {boolean}\n */\n static isValidZone(zone) {\n if (!zone) {\n return false;\n }\n try {\n new Intl.DateTimeFormat(\"en-US\", { timeZone: zone }).format();\n return true;\n } catch (e) {\n return false;\n }\n }\n\n constructor(name) {\n super();\n /** @private **/\n this.zoneName = name;\n /** @private **/\n this.valid = IANAZone.isValidZone(name);\n }\n\n /**\n * The type of zone. `iana` for all instances of `IANAZone`.\n * @override\n * @type {string}\n */\n get type() {\n return \"iana\";\n }\n\n /**\n * The name of this zone (i.e. the IANA zone name).\n * @override\n * @type {string}\n */\n get name() {\n return this.zoneName;\n }\n\n /**\n * Returns whether the offset is known to be fixed for the whole year:\n * Always returns false for all IANA zones.\n * @override\n * @type {boolean}\n */\n get isUniversal() {\n return false;\n }\n\n /**\n * Returns the offset's common name (such as EST) at the specified timestamp\n * @override\n * @param {number} ts - Epoch milliseconds for which to get the name\n * @param {Object} opts - Options to affect the format\n * @param {string} opts.format - What style of offset to return. Accepts 'long' or 'short'.\n * @param {string} opts.locale - What locale to return the offset name in.\n * @return {string}\n */\n offsetName(ts, { format, locale }) {\n return parseZoneInfo(ts, format, locale, this.name);\n }\n\n /**\n * Returns the offset's value as a string\n * @override\n * @param {number} ts - Epoch milliseconds for which to get the offset\n * @param {string} format - What style of offset to return.\n * Accepts 'narrow', 'short', or 'techie'. Returning '+6', '+06:00', or '+0600' respectively\n * @return {string}\n */\n formatOffset(ts, format) {\n return formatOffset(this.offset(ts), format);\n }\n\n /**\n * Return the offset in minutes for this zone at the specified timestamp.\n * @override\n * @param {number} ts - Epoch milliseconds for which to compute the offset\n * @return {number}\n */\n offset(ts) {\n const date = new Date(ts);\n\n if (isNaN(date)) return NaN;\n\n const dtf = makeDTF(this.name);\n let [year, month, day, adOrBc, hour, minute, second] = dtf.formatToParts\n ? partsOffset(dtf, date)\n : hackyOffset(dtf, date);\n\n if (adOrBc === \"BC\") {\n year = -Math.abs(year) + 1;\n }\n\n // because we're using hour12 and https://bugs.chromium.org/p/chromium/issues/detail?id=1025564&can=2&q=%2224%3A00%22%20datetimeformat\n const adjustedHour = hour === 24 ? 0 : hour;\n\n const asUTC = objToLocalTS({\n year,\n month,\n day,\n hour: adjustedHour,\n minute,\n second,\n millisecond: 0,\n });\n\n let asTS = +date;\n const over = asTS % 1000;\n asTS -= over >= 0 ? over : 1000 + over;\n return (asUTC - asTS) / (60 * 1000);\n }\n\n /**\n * Return whether this Zone is equal to another zone\n * @override\n * @param {Zone} otherZone - the zone to compare\n * @return {boolean}\n */\n equals(otherZone) {\n return otherZone.type === \"iana\" && otherZone.name === this.name;\n }\n\n /**\n * Return whether this Zone is valid.\n * @override\n * @type {boolean}\n */\n get isValid() {\n return this.valid;\n }\n}\n", "import { hasLocaleWeekInfo, hasRelative, padStart, roundTo, validateWeekSettings } from \"./util.js\";\nimport * as English from \"./english.js\";\nimport Settings from \"../settings.js\";\nimport DateTime from \"../datetime.js\";\nimport IANAZone from \"../zones/IANAZone.js\";\n\n// todo - remap caching\n\nlet intlLFCache = {};\nfunction getCachedLF(locString, opts = {}) {\n const key = JSON.stringify([locString, opts]);\n let dtf = intlLFCache[key];\n if (!dtf) {\n dtf = new Intl.ListFormat(locString, opts);\n intlLFCache[key] = dtf;\n }\n return dtf;\n}\n\nlet intlDTCache = {};\nfunction getCachedDTF(locString, opts = {}) {\n const key = JSON.stringify([locString, opts]);\n let dtf = intlDTCache[key];\n if (!dtf) {\n dtf = new Intl.DateTimeFormat(locString, opts);\n intlDTCache[key] = dtf;\n }\n return dtf;\n}\n\nlet intlNumCache = {};\nfunction getCachedINF(locString, opts = {}) {\n const key = JSON.stringify([locString, opts]);\n let inf = intlNumCache[key];\n if (!inf) {\n inf = new Intl.NumberFormat(locString, opts);\n intlNumCache[key] = inf;\n }\n return inf;\n}\n\nlet intlRelCache = {};\nfunction getCachedRTF(locString, opts = {}) {\n const { base, ...cacheKeyOpts } = opts; // exclude `base` from the options\n const key = JSON.stringify([locString, cacheKeyOpts]);\n let inf = intlRelCache[key];\n if (!inf) {\n inf = new Intl.RelativeTimeFormat(locString, opts);\n intlRelCache[key] = inf;\n }\n return inf;\n}\n\nlet sysLocaleCache = null;\nfunction systemLocale() {\n if (sysLocaleCache) {\n return sysLocaleCache;\n } else {\n sysLocaleCache = new Intl.DateTimeFormat().resolvedOptions().locale;\n return sysLocaleCache;\n }\n}\n\nlet weekInfoCache = {};\nfunction getCachedWeekInfo(locString) {\n let data = weekInfoCache[locString];\n if (!data) {\n const locale = new Intl.Locale(locString);\n // browsers currently implement this as a property, but spec says it should be a getter function\n data = \"getWeekInfo\" in locale ? locale.getWeekInfo() : locale.weekInfo;\n weekInfoCache[locString] = data;\n }\n return data;\n}\n\nfunction parseLocaleString(localeStr) {\n // I really want to avoid writing a BCP 47 parser\n // see, e.g. https://github.com/wooorm/bcp-47\n // Instead, we'll do this:\n\n // a) if the string has no -u extensions, just leave it alone\n // b) if it does, use Intl to resolve everything\n // c) if Intl fails, try again without the -u\n\n // private subtags and unicode subtags have ordering requirements,\n // and we're not properly parsing this, so just strip out the\n // private ones if they exist.\n const xIndex = localeStr.indexOf(\"-x-\");\n if (xIndex !== -1) {\n localeStr = localeStr.substring(0, xIndex);\n }\n\n const uIndex = localeStr.indexOf(\"-u-\");\n if (uIndex === -1) {\n return [localeStr];\n } else {\n let options;\n let selectedStr;\n try {\n options = getCachedDTF(localeStr).resolvedOptions();\n selectedStr = localeStr;\n } catch (e) {\n const smaller = localeStr.substring(0, uIndex);\n options = getCachedDTF(smaller).resolvedOptions();\n selectedStr = smaller;\n }\n\n const { numberingSystem, calendar } = options;\n return [selectedStr, numberingSystem, calendar];\n }\n}\n\nfunction intlConfigString(localeStr, numberingSystem, outputCalendar) {\n if (outputCalendar || numberingSystem) {\n if (!localeStr.includes(\"-u-\")) {\n localeStr += \"-u\";\n }\n\n if (outputCalendar) {\n localeStr += `-ca-${outputCalendar}`;\n }\n\n if (numberingSystem) {\n localeStr += `-nu-${numberingSystem}`;\n }\n return localeStr;\n } else {\n return localeStr;\n }\n}\n\nfunction mapMonths(f) {\n const ms = [];\n for (let i = 1; i <= 12; i++) {\n const dt = DateTime.utc(2009, i, 1);\n ms.push(f(dt));\n }\n return ms;\n}\n\nfunction mapWeekdays(f) {\n const ms = [];\n for (let i = 1; i <= 7; i++) {\n const dt = DateTime.utc(2016, 11, 13 + i);\n ms.push(f(dt));\n }\n return ms;\n}\n\nfunction listStuff(loc, length, englishFn, intlFn) {\n const mode = loc.listingMode();\n\n if (mode === \"error\") {\n return null;\n } else if (mode === \"en\") {\n return englishFn(length);\n } else {\n return intlFn(length);\n }\n}\n\nfunction supportsFastNumbers(loc) {\n if (loc.numberingSystem && loc.numberingSystem !== \"latn\") {\n return false;\n } else {\n return (\n loc.numberingSystem === \"latn\" ||\n !loc.locale ||\n loc.locale.startsWith(\"en\") ||\n new Intl.DateTimeFormat(loc.intl).resolvedOptions().numberingSystem === \"latn\"\n );\n }\n}\n\n/**\n * @private\n */\n\nclass PolyNumberFormatter {\n constructor(intl, forceSimple, opts) {\n this.padTo = opts.padTo || 0;\n this.floor = opts.floor || false;\n\n const { padTo, floor, ...otherOpts } = opts;\n\n if (!forceSimple || Object.keys(otherOpts).length > 0) {\n const intlOpts = { useGrouping: false, ...opts };\n if (opts.padTo > 0) intlOpts.minimumIntegerDigits = opts.padTo;\n this.inf = getCachedINF(intl, intlOpts);\n }\n }\n\n format(i) {\n if (this.inf) {\n const fixed = this.floor ? Math.floor(i) : i;\n return this.inf.format(fixed);\n } else {\n // to match the browser's numberformatter defaults\n const fixed = this.floor ? Math.floor(i) : roundTo(i, 3);\n return padStart(fixed, this.padTo);\n }\n }\n}\n\n/**\n * @private\n */\n\nclass PolyDateFormatter {\n constructor(dt, intl, opts) {\n this.opts = opts;\n this.originalZone = undefined;\n\n let z = undefined;\n if (this.opts.timeZone) {\n // Don't apply any workarounds if a timeZone is explicitly provided in opts\n this.dt = dt;\n } else if (dt.zone.type === \"fixed\") {\n // UTC-8 or Etc/UTC-8 are not part of tzdata, only Etc/GMT+8 and the like.\n // That is why fixed-offset TZ is set to that unless it is:\n // 1. Representing offset 0 when UTC is used to maintain previous behavior and does not become GMT.\n // 2. Unsupported by the browser:\n // - some do not support Etc/\n // - < Etc/GMT-14, > Etc/GMT+12, and 30-minute or 45-minute offsets are not part of tzdata\n const gmtOffset = -1 * (dt.offset / 60);\n const offsetZ = gmtOffset >= 0 ? `Etc/GMT+${gmtOffset}` : `Etc/GMT${gmtOffset}`;\n if (dt.offset !== 0 && IANAZone.create(offsetZ).valid) {\n z = offsetZ;\n this.dt = dt;\n } else {\n // Not all fixed-offset zones like Etc/+4:30 are present in tzdata so\n // we manually apply the offset and substitute the zone as needed.\n z = \"UTC\";\n this.dt = dt.offset === 0 ? dt : dt.setZone(\"UTC\").plus({ minutes: dt.offset });\n this.originalZone = dt.zone;\n }\n } else if (dt.zone.type === \"system\") {\n this.dt = dt;\n } else if (dt.zone.type === \"iana\") {\n this.dt = dt;\n z = dt.zone.name;\n } else {\n // Custom zones can have any offset / offsetName so we just manually\n // apply the offset and substitute the zone as needed.\n z = \"UTC\";\n this.dt = dt.setZone(\"UTC\").plus({ minutes: dt.offset });\n this.originalZone = dt.zone;\n }\n\n const intlOpts = { ...this.opts };\n intlOpts.timeZone = intlOpts.timeZone || z;\n this.dtf = getCachedDTF(intl, intlOpts);\n }\n\n format() {\n if (this.originalZone) {\n // If we have to substitute in the actual zone name, we have to use\n // formatToParts so that the timezone can be replaced.\n return this.formatToParts()\n .map(({ value }) => value)\n .join(\"\");\n }\n return this.dtf.format(this.dt.toJSDate());\n }\n\n formatToParts() {\n const parts = this.dtf.formatToParts(this.dt.toJSDate());\n if (this.originalZone) {\n return parts.map((part) => {\n if (part.type === \"timeZoneName\") {\n const offsetName = this.originalZone.offsetName(this.dt.ts, {\n locale: this.dt.locale,\n format: this.opts.timeZoneName,\n });\n return {\n ...part,\n value: offsetName,\n };\n } else {\n return part;\n }\n });\n }\n return parts;\n }\n\n resolvedOptions() {\n return this.dtf.resolvedOptions();\n }\n}\n\n/**\n * @private\n */\nclass PolyRelFormatter {\n constructor(intl, isEnglish, opts) {\n this.opts = { style: \"long\", ...opts };\n if (!isEnglish && hasRelative()) {\n this.rtf = getCachedRTF(intl, opts);\n }\n }\n\n format(count, unit) {\n if (this.rtf) {\n return this.rtf.format(count, unit);\n } else {\n return English.formatRelativeTime(unit, count, this.opts.numeric, this.opts.style !== \"long\");\n }\n }\n\n formatToParts(count, unit) {\n if (this.rtf) {\n return this.rtf.formatToParts(count, unit);\n } else {\n return [];\n }\n }\n}\n\nconst fallbackWeekSettings = {\n firstDay: 1,\n minimalDays: 4,\n weekend: [6, 7],\n};\n\n/**\n * @private\n */\n\nexport default class Locale {\n static fromOpts(opts) {\n return Locale.create(\n opts.locale,\n opts.numberingSystem,\n opts.outputCalendar,\n opts.weekSettings,\n opts.defaultToEN\n );\n }\n\n static create(locale, numberingSystem, outputCalendar, weekSettings, defaultToEN = false) {\n const specifiedLocale = locale || Settings.defaultLocale;\n // the system locale is useful for human-readable strings but annoying for parsing/formatting known formats\n const localeR = specifiedLocale || (defaultToEN ? \"en-US\" : systemLocale());\n const numberingSystemR = numberingSystem || Settings.defaultNumberingSystem;\n const outputCalendarR = outputCalendar || Settings.defaultOutputCalendar;\n const weekSettingsR = validateWeekSettings(weekSettings) || Settings.defaultWeekSettings;\n return new Locale(localeR, numberingSystemR, outputCalendarR, weekSettingsR, specifiedLocale);\n }\n\n static resetCache() {\n sysLocaleCache = null;\n intlDTCache = {};\n intlNumCache = {};\n intlRelCache = {};\n }\n\n static fromObject({ locale, numberingSystem, outputCalendar, weekSettings } = {}) {\n return Locale.create(locale, numberingSystem, outputCalendar, weekSettings);\n }\n\n constructor(locale, numbering, outputCalendar, weekSettings, specifiedLocale) {\n const [parsedLocale, parsedNumberingSystem, parsedOutputCalendar] = parseLocaleString(locale);\n\n this.locale = parsedLocale;\n this.numberingSystem = numbering || parsedNumberingSystem || null;\n this.outputCalendar = outputCalendar || parsedOutputCalendar || null;\n this.weekSettings = weekSettings;\n this.intl = intlConfigString(this.locale, this.numberingSystem, this.outputCalendar);\n\n this.weekdaysCache = { format: {}, standalone: {} };\n this.monthsCache = { format: {}, standalone: {} };\n this.meridiemCache = null;\n this.eraCache = {};\n\n this.specifiedLocale = specifiedLocale;\n this.fastNumbersCached = null;\n }\n\n get fastNumbers() {\n if (this.fastNumbersCached == null) {\n this.fastNumbersCached = supportsFastNumbers(this);\n }\n\n return this.fastNumbersCached;\n }\n\n listingMode() {\n const isActuallyEn = this.isEnglish();\n const hasNoWeirdness =\n (this.numberingSystem === null || this.numberingSystem === \"latn\") &&\n (this.outputCalendar === null || this.outputCalendar === \"gregory\");\n return isActuallyEn && hasNoWeirdness ? \"en\" : \"intl\";\n }\n\n clone(alts) {\n if (!alts || Object.getOwnPropertyNames(alts).length === 0) {\n return this;\n } else {\n return Locale.create(\n alts.locale || this.specifiedLocale,\n alts.numberingSystem || this.numberingSystem,\n alts.outputCalendar || this.outputCalendar,\n validateWeekSettings(alts.weekSettings) || this.weekSettings,\n alts.defaultToEN || false\n );\n }\n }\n\n redefaultToEN(alts = {}) {\n return this.clone({ ...alts, defaultToEN: true });\n }\n\n redefaultToSystem(alts = {}) {\n return this.clone({ ...alts, defaultToEN: false });\n }\n\n months(length, format = false) {\n return listStuff(this, length, English.months, () => {\n const intl = format ? { month: length, day: \"numeric\" } : { month: length },\n formatStr = format ? \"format\" : \"standalone\";\n if (!this.monthsCache[formatStr][length]) {\n this.monthsCache[formatStr][length] = mapMonths((dt) => this.extract(dt, intl, \"month\"));\n }\n return this.monthsCache[formatStr][length];\n });\n }\n\n weekdays(length, format = false) {\n return listStuff(this, length, English.weekdays, () => {\n const intl = format\n ? { weekday: length, year: \"numeric\", month: \"long\", day: \"numeric\" }\n : { weekday: length },\n formatStr = format ? \"format\" : \"standalone\";\n if (!this.weekdaysCache[formatStr][length]) {\n this.weekdaysCache[formatStr][length] = mapWeekdays((dt) =>\n this.extract(dt, intl, \"weekday\")\n );\n }\n return this.weekdaysCache[formatStr][length];\n });\n }\n\n meridiems() {\n return listStuff(\n this,\n undefined,\n () => English.meridiems,\n () => {\n // In theory there could be aribitrary day periods. We're gonna assume there are exactly two\n // for AM and PM. This is probably wrong, but it's makes parsing way easier.\n if (!this.meridiemCache) {\n const intl = { hour: \"numeric\", hourCycle: \"h12\" };\n this.meridiemCache = [DateTime.utc(2016, 11, 13, 9), DateTime.utc(2016, 11, 13, 19)].map(\n (dt) => this.extract(dt, intl, \"dayperiod\")\n );\n }\n\n return this.meridiemCache;\n }\n );\n }\n\n eras(length) {\n return listStuff(this, length, English.eras, () => {\n const intl = { era: length };\n\n // This is problematic. Different calendars are going to define eras totally differently. What I need is the minimum set of dates\n // to definitely enumerate them.\n if (!this.eraCache[length]) {\n this.eraCache[length] = [DateTime.utc(-40, 1, 1), DateTime.utc(2017, 1, 1)].map((dt) =>\n this.extract(dt, intl, \"era\")\n );\n }\n\n return this.eraCache[length];\n });\n }\n\n extract(dt, intlOpts, field) {\n const df = this.dtFormatter(dt, intlOpts),\n results = df.formatToParts(),\n matching = results.find((m) => m.type.toLowerCase() === field);\n return matching ? matching.value : null;\n }\n\n numberFormatter(opts = {}) {\n // this forcesimple option is never used (the only caller short-circuits on it, but it seems safer to leave)\n // (in contrast, the rest of the condition is used heavily)\n return new PolyNumberFormatter(this.intl, opts.forceSimple || this.fastNumbers, opts);\n }\n\n dtFormatter(dt, intlOpts = {}) {\n return new PolyDateFormatter(dt, this.intl, intlOpts);\n }\n\n relFormatter(opts = {}) {\n return new PolyRelFormatter(this.intl, this.isEnglish(), opts);\n }\n\n listFormatter(opts = {}) {\n return getCachedLF(this.intl, opts);\n }\n\n isEnglish() {\n return (\n this.locale === \"en\" ||\n this.locale.toLowerCase() === \"en-us\" ||\n new Intl.DateTimeFormat(this.intl).resolvedOptions().locale.startsWith(\"en-us\")\n );\n }\n\n getWeekSettings() {\n if (this.weekSettings) {\n return this.weekSettings;\n } else if (!hasLocaleWeekInfo()) {\n return fallbackWeekSettings;\n } else {\n return getCachedWeekInfo(this.locale);\n }\n }\n\n getStartOfWeek() {\n return this.getWeekSettings().firstDay;\n }\n\n getMinDaysInFirstWeek() {\n return this.getWeekSettings().minimalDays;\n }\n\n getWeekendDays() {\n return this.getWeekSettings().weekend;\n }\n\n equals(other) {\n return (\n this.locale === other.locale &&\n this.numberingSystem === other.numberingSystem &&\n this.outputCalendar === other.outputCalendar\n );\n }\n\n toString() {\n return `Locale(${this.locale}, ${this.numberingSystem}, ${this.outputCalendar})`;\n }\n}\n", "import { formatOffset, signedOffset } from \"../impl/util.js\";\nimport Zone from \"../zone.js\";\n\nlet singleton = null;\n\n/**\n * A zone with a fixed offset (meaning no DST)\n * @implements {Zone}\n */\nexport default class FixedOffsetZone extends Zone {\n /**\n * Get a singleton instance of UTC\n * @return {FixedOffsetZone}\n */\n static get utcInstance() {\n if (singleton === null) {\n singleton = new FixedOffsetZone(0);\n }\n return singleton;\n }\n\n /**\n * Get an instance with a specified offset\n * @param {number} offset - The offset in minutes\n * @return {FixedOffsetZone}\n */\n static instance(offset) {\n return offset === 0 ? FixedOffsetZone.utcInstance : new FixedOffsetZone(offset);\n }\n\n /**\n * Get an instance of FixedOffsetZone from a UTC offset string, like \"UTC+6\"\n * @param {string} s - The offset string to parse\n * @example FixedOffsetZone.parseSpecifier(\"UTC+6\")\n * @example FixedOffsetZone.parseSpecifier(\"UTC+06\")\n * @example FixedOffsetZone.parseSpecifier(\"UTC-6:00\")\n * @return {FixedOffsetZone}\n */\n static parseSpecifier(s) {\n if (s) {\n const r = s.match(/^utc(?:([+-]\\d{1,2})(?::(\\d{2}))?)?$/i);\n if (r) {\n return new FixedOffsetZone(signedOffset(r[1], r[2]));\n }\n }\n return null;\n }\n\n constructor(offset) {\n super();\n /** @private **/\n this.fixed = offset;\n }\n\n /**\n * The type of zone. `fixed` for all instances of `FixedOffsetZone`.\n * @override\n * @type {string}\n */\n get type() {\n return \"fixed\";\n }\n\n /**\n * The name of this zone.\n * All fixed zones' names always start with \"UTC\" (plus optional offset)\n * @override\n * @type {string}\n */\n get name() {\n return this.fixed === 0 ? \"UTC\" : `UTC${formatOffset(this.fixed, \"narrow\")}`;\n }\n\n /**\n * The IANA name of this zone, i.e. `Etc/UTC` or `Etc/GMT+/-nn`\n *\n * @override\n * @type {string}\n */\n get ianaName() {\n if (this.fixed === 0) {\n return \"Etc/UTC\";\n } else {\n return `Etc/GMT${formatOffset(-this.fixed, \"narrow\")}`;\n }\n }\n\n /**\n * Returns the offset's common name at the specified timestamp.\n *\n * For fixed offset zones this equals to the zone name.\n * @override\n */\n offsetName() {\n return this.name;\n }\n\n /**\n * Returns the offset's value as a string\n * @override\n * @param {number} ts - Epoch milliseconds for which to get the offset\n * @param {string} format - What style of offset to return.\n * Accepts 'narrow', 'short', or 'techie'. Returning '+6', '+06:00', or '+0600' respectively\n * @return {string}\n */\n formatOffset(ts, format) {\n return formatOffset(this.fixed, format);\n }\n\n /**\n * Returns whether the offset is known to be fixed for the whole year:\n * Always returns true for all fixed offset zones.\n * @override\n * @type {boolean}\n */\n get isUniversal() {\n return true;\n }\n\n /**\n * Return the offset in minutes for this zone at the specified timestamp.\n *\n * For fixed offset zones, this is constant and does not depend on a timestamp.\n * @override\n * @return {number}\n */\n offset() {\n return this.fixed;\n }\n\n /**\n * Return whether this Zone is equal to another zone (i.e. also fixed and same offset)\n * @override\n * @param {Zone} otherZone - the zone to compare\n * @return {boolean}\n */\n equals(otherZone) {\n return otherZone.type === \"fixed\" && otherZone.fixed === this.fixed;\n }\n\n /**\n * Return whether this Zone is valid:\n * All fixed offset zones are valid.\n * @override\n * @type {boolean}\n */\n get isValid() {\n return true;\n }\n}\n", "import Zone from \"../zone.js\";\n\n/**\n * A zone that failed to parse. You should never need to instantiate this.\n * @implements {Zone}\n */\nexport default class InvalidZone extends Zone {\n constructor(zoneName) {\n super();\n /** @private */\n this.zoneName = zoneName;\n }\n\n /** @override **/\n get type() {\n return \"invalid\";\n }\n\n /** @override **/\n get name() {\n return this.zoneName;\n }\n\n /** @override **/\n get isUniversal() {\n return false;\n }\n\n /** @override **/\n offsetName() {\n return null;\n }\n\n /** @override **/\n formatOffset() {\n return \"\";\n }\n\n /** @override **/\n offset() {\n return NaN;\n }\n\n /** @override **/\n equals() {\n return false;\n }\n\n /** @override **/\n get isValid() {\n return false;\n }\n}\n", "/**\n * @private\n */\n\nimport Zone from \"../zone.js\";\nimport IANAZone from \"../zones/IANAZone.js\";\nimport FixedOffsetZone from \"../zones/fixedOffsetZone.js\";\nimport InvalidZone from \"../zones/invalidZone.js\";\n\nimport { isUndefined, isString, isNumber } from \"./util.js\";\nimport SystemZone from \"../zones/systemZone.js\";\n\nexport function normalizeZone(input, defaultZone) {\n let offset;\n if (isUndefined(input) || input === null) {\n return defaultZone;\n } else if (input instanceof Zone) {\n return input;\n } else if (isString(input)) {\n const lowered = input.toLowerCase();\n if (lowered === \"default\") return defaultZone;\n else if (lowered === \"local\" || lowered === \"system\") return SystemZone.instance;\n else if (lowered === \"utc\" || lowered === \"gmt\") return FixedOffsetZone.utcInstance;\n else return FixedOffsetZone.parseSpecifier(lowered) || IANAZone.create(input);\n } else if (isNumber(input)) {\n return FixedOffsetZone.instance(input);\n } else if (typeof input === \"object\" && \"offset\" in input && typeof input.offset === \"function\") {\n // This is dumb, but the instanceof check above doesn't seem to really work\n // so we're duck checking it\n return input;\n } else {\n return new InvalidZone(input);\n }\n}\n", "const numberingSystems = {\n arab: \"[\\u0660-\\u0669]\",\n arabext: \"[\\u06F0-\\u06F9]\",\n bali: \"[\\u1B50-\\u1B59]\",\n beng: \"[\\u09E6-\\u09EF]\",\n deva: \"[\\u0966-\\u096F]\",\n fullwide: \"[\\uFF10-\\uFF19]\",\n gujr: \"[\\u0AE6-\\u0AEF]\",\n hanidec: \"[\u3007|\u4E00|\u4E8C|\u4E09|\u56DB|\u4E94|\u516D|\u4E03|\u516B|\u4E5D]\",\n khmr: \"[\\u17E0-\\u17E9]\",\n knda: \"[\\u0CE6-\\u0CEF]\",\n laoo: \"[\\u0ED0-\\u0ED9]\",\n limb: \"[\\u1946-\\u194F]\",\n mlym: \"[\\u0D66-\\u0D6F]\",\n mong: \"[\\u1810-\\u1819]\",\n mymr: \"[\\u1040-\\u1049]\",\n orya: \"[\\u0B66-\\u0B6F]\",\n tamldec: \"[\\u0BE6-\\u0BEF]\",\n telu: \"[\\u0C66-\\u0C6F]\",\n thai: \"[\\u0E50-\\u0E59]\",\n tibt: \"[\\u0F20-\\u0F29]\",\n latn: \"\\\\d\",\n};\n\nconst numberingSystemsUTF16 = {\n arab: [1632, 1641],\n arabext: [1776, 1785],\n bali: [6992, 7001],\n beng: [2534, 2543],\n deva: [2406, 2415],\n fullwide: [65296, 65303],\n gujr: [2790, 2799],\n khmr: [6112, 6121],\n knda: [3302, 3311],\n laoo: [3792, 3801],\n limb: [6470, 6479],\n mlym: [3430, 3439],\n mong: [6160, 6169],\n mymr: [4160, 4169],\n orya: [2918, 2927],\n tamldec: [3046, 3055],\n telu: [3174, 3183],\n thai: [3664, 3673],\n tibt: [3872, 3881],\n};\n\nconst hanidecChars = numberingSystems.hanidec.replace(/[\\[|\\]]/g, \"\").split(\"\");\n\nexport function parseDigits(str) {\n let value = parseInt(str, 10);\n if (isNaN(value)) {\n value = \"\";\n for (let i = 0; i < str.length; i++) {\n const code = str.charCodeAt(i);\n\n if (str[i].search(numberingSystems.hanidec) !== -1) {\n value += hanidecChars.indexOf(str[i]);\n } else {\n for (const key in numberingSystemsUTF16) {\n const [min, max] = numberingSystemsUTF16[key];\n if (code >= min && code <= max) {\n value += code - min;\n }\n }\n }\n }\n return parseInt(value, 10);\n } else {\n return value;\n }\n}\n\n// cache of {numberingSystem: {append: regex}}\nlet digitRegexCache = {};\nexport function resetDigitRegexCache() {\n digitRegexCache = {};\n}\n\nexport function digitRegex({ numberingSystem }, append = \"\") {\n const ns = numberingSystem || \"latn\";\n\n if (!digitRegexCache[ns]) {\n digitRegexCache[ns] = {};\n }\n if (!digitRegexCache[ns][append]) {\n digitRegexCache[ns][append] = new RegExp(`${numberingSystems[ns]}${append}`);\n }\n\n return digitRegexCache[ns][append];\n}\n", "import SystemZone from \"./zones/systemZone.js\";\nimport IANAZone from \"./zones/IANAZone.js\";\nimport Locale from \"./impl/locale.js\";\nimport DateTime from \"./datetime.js\";\n\nimport { normalizeZone } from \"./impl/zoneUtil.js\";\nimport { validateWeekSettings } from \"./impl/util.js\";\nimport { resetDigitRegexCache } from \"./impl/digits.js\";\n\nlet now = () => Date.now(),\n defaultZone = \"system\",\n defaultLocale = null,\n defaultNumberingSystem = null,\n defaultOutputCalendar = null,\n twoDigitCutoffYear = 60,\n throwOnInvalid,\n defaultWeekSettings = null;\n\n/**\n * Settings contains static getters and setters that control Luxon's overall behavior. Luxon is a simple library with few options, but the ones it does have live here.\n */\nexport default class Settings {\n /**\n * Get the callback for returning the current timestamp.\n * @type {function}\n */\n static get now() {\n return now;\n }\n\n /**\n * Set the callback for returning the current timestamp.\n * The function should return a number, which will be interpreted as an Epoch millisecond count\n * @type {function}\n * @example Settings.now = () => Date.now() + 3000 // pretend it is 3 seconds in the future\n * @example Settings.now = () => 0 // always pretend it's Jan 1, 1970 at midnight in UTC time\n */\n static set now(n) {\n now = n;\n }\n\n /**\n * Set the default time zone to create DateTimes in. Does not affect existing instances.\n * Use the value \"system\" to reset this value to the system's time zone.\n * @type {string}\n */\n static set defaultZone(zone) {\n defaultZone = zone;\n }\n\n /**\n * Get the default time zone object currently used to create DateTimes. Does not affect existing instances.\n * The default value is the system's time zone (the one set on the machine that runs this code).\n * @type {Zone}\n */\n static get defaultZone() {\n return normalizeZone(defaultZone, SystemZone.instance);\n }\n\n /**\n * Get the default locale to create DateTimes with. Does not affect existing instances.\n * @type {string}\n */\n static get defaultLocale() {\n return defaultLocale;\n }\n\n /**\n * Set the default locale to create DateTimes with. Does not affect existing instances.\n * @type {string}\n */\n static set defaultLocale(locale) {\n defaultLocale = locale;\n }\n\n /**\n * Get the default numbering system to create DateTimes with. Does not affect existing instances.\n * @type {string}\n */\n static get defaultNumberingSystem() {\n return defaultNumberingSystem;\n }\n\n /**\n * Set the default numbering system to create DateTimes with. Does not affect existing instances.\n * @type {string}\n */\n static set defaultNumberingSystem(numberingSystem) {\n defaultNumberingSystem = numberingSystem;\n }\n\n /**\n * Get the default output calendar to create DateTimes with. Does not affect existing instances.\n * @type {string}\n */\n static get defaultOutputCalendar() {\n return defaultOutputCalendar;\n }\n\n /**\n * Set the default output calendar to create DateTimes with. Does not affect existing instances.\n * @type {string}\n */\n static set defaultOutputCalendar(outputCalendar) {\n defaultOutputCalendar = outputCalendar;\n }\n\n /**\n * @typedef {Object} WeekSettings\n * @property {number} firstDay\n * @property {number} minimalDays\n * @property {number[]} weekend\n */\n\n /**\n * @return {WeekSettings|null}\n */\n static get defaultWeekSettings() {\n return defaultWeekSettings;\n }\n\n /**\n * Allows overriding the default locale week settings, i.e. the start of the week, the weekend and\n * how many days are required in the first week of a year.\n * Does not affect existing instances.\n *\n * @param {WeekSettings|null} weekSettings\n */\n static set defaultWeekSettings(weekSettings) {\n defaultWeekSettings = validateWeekSettings(weekSettings);\n }\n\n /**\n * Get the cutoff year for whether a 2-digit year string is interpreted in the current or previous century. Numbers higher than the cutoff will be considered to mean 19xx and numbers lower or equal to the cutoff will be considered 20xx.\n * @type {number}\n */\n static get twoDigitCutoffYear() {\n return twoDigitCutoffYear;\n }\n\n /**\n * Set the cutoff year for whether a 2-digit year string is interpreted in the current or previous century. Numbers higher than the cutoff will be considered to mean 19xx and numbers lower or equal to the cutoff will be considered 20xx.\n * @type {number}\n * @example Settings.twoDigitCutoffYear = 0 // all 'yy' are interpreted as 20th century\n * @example Settings.twoDigitCutoffYear = 99 // all 'yy' are interpreted as 21st century\n * @example Settings.twoDigitCutoffYear = 50 // '49' -> 2049; '50' -> 1950\n * @example Settings.twoDigitCutoffYear = 1950 // interpreted as 50\n * @example Settings.twoDigitCutoffYear = 2050 // ALSO interpreted as 50\n */\n static set twoDigitCutoffYear(cutoffYear) {\n twoDigitCutoffYear = cutoffYear % 100;\n }\n\n /**\n * Get whether Luxon will throw when it encounters invalid DateTimes, Durations, or Intervals\n * @type {boolean}\n */\n static get throwOnInvalid() {\n return throwOnInvalid;\n }\n\n /**\n * Set whether Luxon will throw when it encounters invalid DateTimes, Durations, or Intervals\n * @type {boolean}\n */\n static set throwOnInvalid(t) {\n throwOnInvalid = t;\n }\n\n /**\n * Reset Luxon's global caches. Should only be necessary in testing scenarios.\n * @return {void}\n */\n static resetCaches() {\n Locale.resetCache();\n IANAZone.resetCache();\n DateTime.resetCache();\n resetDigitRegexCache();\n }\n}\n", "export default class Invalid {\n constructor(reason, explanation) {\n this.reason = reason;\n this.explanation = explanation;\n }\n\n toMessage() {\n if (this.explanation) {\n return `${this.reason}: ${this.explanation}`;\n } else {\n return this.reason;\n }\n }\n}\n", "import {\n integerBetween,\n isLeapYear,\n timeObject,\n daysInYear,\n daysInMonth,\n weeksInWeekYear,\n isInteger,\n isUndefined,\n} from \"./util.js\";\nimport Invalid from \"./invalid.js\";\nimport { ConflictingSpecificationError } from \"../errors.js\";\n\nconst nonLeapLadder = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334],\n leapLadder = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335];\n\nfunction unitOutOfRange(unit, value) {\n return new Invalid(\n \"unit out of range\",\n `you specified ${value} (of type ${typeof value}) as a ${unit}, which is invalid`\n );\n}\n\nexport function dayOfWeek(year, month, day) {\n const d = new Date(Date.UTC(year, month - 1, day));\n\n if (year < 100 && year >= 0) {\n d.setUTCFullYear(d.getUTCFullYear() - 1900);\n }\n\n const js = d.getUTCDay();\n\n return js === 0 ? 7 : js;\n}\n\nfunction computeOrdinal(year, month, day) {\n return day + (isLeapYear(year) ? leapLadder : nonLeapLadder)[month - 1];\n}\n\nfunction uncomputeOrdinal(year, ordinal) {\n const table = isLeapYear(year) ? leapLadder : nonLeapLadder,\n month0 = table.findIndex((i) => i < ordinal),\n day = ordinal - table[month0];\n return { month: month0 + 1, day };\n}\n\nexport function isoWeekdayToLocal(isoWeekday, startOfWeek) {\n return ((isoWeekday - startOfWeek + 7) % 7) + 1;\n}\n\n/**\n * @private\n */\n\nexport function gregorianToWeek(gregObj, minDaysInFirstWeek = 4, startOfWeek = 1) {\n const { year, month, day } = gregObj,\n ordinal = computeOrdinal(year, month, day),\n weekday = isoWeekdayToLocal(dayOfWeek(year, month, day), startOfWeek);\n\n let weekNumber = Math.floor((ordinal - weekday + 14 - minDaysInFirstWeek) / 7),\n weekYear;\n\n if (weekNumber < 1) {\n weekYear = year - 1;\n weekNumber = weeksInWeekYear(weekYear, minDaysInFirstWeek, startOfWeek);\n } else if (weekNumber > weeksInWeekYear(year, minDaysInFirstWeek, startOfWeek)) {\n weekYear = year + 1;\n weekNumber = 1;\n } else {\n weekYear = year;\n }\n\n return { weekYear, weekNumber, weekday, ...timeObject(gregObj) };\n}\n\nexport function weekToGregorian(weekData, minDaysInFirstWeek = 4, startOfWeek = 1) {\n const { weekYear, weekNumber, weekday } = weekData,\n weekdayOfJan4 = isoWeekdayToLocal(dayOfWeek(weekYear, 1, minDaysInFirstWeek), startOfWeek),\n yearInDays = daysInYear(weekYear);\n\n let ordinal = weekNumber * 7 + weekday - weekdayOfJan4 - 7 + minDaysInFirstWeek,\n year;\n\n if (ordinal < 1) {\n year = weekYear - 1;\n ordinal += daysInYear(year);\n } else if (ordinal > yearInDays) {\n year = weekYear + 1;\n ordinal -= daysInYear(weekYear);\n } else {\n year = weekYear;\n }\n\n const { month, day } = uncomputeOrdinal(year, ordinal);\n return { year, month, day, ...timeObject(weekData) };\n}\n\nexport function gregorianToOrdinal(gregData) {\n const { year, month, day } = gregData;\n const ordinal = computeOrdinal(year, month, day);\n return { year, ordinal, ...timeObject(gregData) };\n}\n\nexport function ordinalToGregorian(ordinalData) {\n const { year, ordinal } = ordinalData;\n const { month, day } = uncomputeOrdinal(year, ordinal);\n return { year, month, day, ...timeObject(ordinalData) };\n}\n\n/**\n * Check if local week units like localWeekday are used in obj.\n * If so, validates that they are not mixed with ISO week units and then copies them to the normal week unit properties.\n * Modifies obj in-place!\n * @param obj the object values\n */\nexport function usesLocalWeekValues(obj, loc) {\n const hasLocaleWeekData =\n !isUndefined(obj.localWeekday) ||\n !isUndefined(obj.localWeekNumber) ||\n !isUndefined(obj.localWeekYear);\n if (hasLocaleWeekData) {\n const hasIsoWeekData =\n !isUndefined(obj.weekday) || !isUndefined(obj.weekNumber) || !isUndefined(obj.weekYear);\n\n if (hasIsoWeekData) {\n throw new ConflictingSpecificationError(\n \"Cannot mix locale-based week fields with ISO-based week fields\"\n );\n }\n if (!isUndefined(obj.localWeekday)) obj.weekday = obj.localWeekday;\n if (!isUndefined(obj.localWeekNumber)) obj.weekNumber = obj.localWeekNumber;\n if (!isUndefined(obj.localWeekYear)) obj.weekYear = obj.localWeekYear;\n delete obj.localWeekday;\n delete obj.localWeekNumber;\n delete obj.localWeekYear;\n return {\n minDaysInFirstWeek: loc.getMinDaysInFirstWeek(),\n startOfWeek: loc.getStartOfWeek(),\n };\n } else {\n return { minDaysInFirstWeek: 4, startOfWeek: 1 };\n }\n}\n\nexport function hasInvalidWeekData(obj, minDaysInFirstWeek = 4, startOfWeek = 1) {\n const validYear = isInteger(obj.weekYear),\n validWeek = integerBetween(\n obj.weekNumber,\n 1,\n weeksInWeekYear(obj.weekYear, minDaysInFirstWeek, startOfWeek)\n ),\n validWeekday = integerBetween(obj.weekday, 1, 7);\n\n if (!validYear) {\n return unitOutOfRange(\"weekYear\", obj.weekYear);\n } else if (!validWeek) {\n return unitOutOfRange(\"week\", obj.weekNumber);\n } else if (!validWeekday) {\n return unitOutOfRange(\"weekday\", obj.weekday);\n } else return false;\n}\n\nexport function hasInvalidOrdinalData(obj) {\n const validYear = isInteger(obj.year),\n validOrdinal = integerBetween(obj.ordinal, 1, daysInYear(obj.year));\n\n if (!validYear) {\n return unitOutOfRange(\"year\", obj.year);\n } else if (!validOrdinal) {\n return unitOutOfRange(\"ordinal\", obj.ordinal);\n } else return false;\n}\n\nexport function hasInvalidGregorianData(obj) {\n const validYear = isInteger(obj.year),\n validMonth = integerBetween(obj.month, 1, 12),\n validDay = integerBetween(obj.day, 1, daysInMonth(obj.year, obj.month));\n\n if (!validYear) {\n return unitOutOfRange(\"year\", obj.year);\n } else if (!validMonth) {\n return unitOutOfRange(\"month\", obj.month);\n } else if (!validDay) {\n return unitOutOfRange(\"day\", obj.day);\n } else return false;\n}\n\nexport function hasInvalidTimeData(obj) {\n const { hour, minute, second, millisecond } = obj;\n const validHour =\n integerBetween(hour, 0, 23) ||\n (hour === 24 && minute === 0 && second === 0 && millisecond === 0),\n validMinute = integerBetween(minute, 0, 59),\n validSecond = integerBetween(second, 0, 59),\n validMillisecond = integerBetween(millisecond, 0, 999);\n\n if (!validHour) {\n return unitOutOfRange(\"hour\", hour);\n } else if (!validMinute) {\n return unitOutOfRange(\"minute\", minute);\n } else if (!validSecond) {\n return unitOutOfRange(\"second\", second);\n } else if (!validMillisecond) {\n return unitOutOfRange(\"millisecond\", millisecond);\n } else return false;\n}\n", "/*\n This is just a junk drawer, containing anything used across multiple classes.\n Because Luxon is small(ish), this should stay small and we won't worry about splitting\n it up into, say, parsingUtil.js and basicUtil.js and so on. But they are divided up by feature area.\n*/\n\nimport { InvalidArgumentError } from \"../errors.js\";\nimport Settings from \"../settings.js\";\nimport { dayOfWeek, isoWeekdayToLocal } from \"./conversions.js\";\n\n/**\n * @private\n */\n\n// TYPES\n\nexport function isUndefined(o) {\n return typeof o === \"undefined\";\n}\n\nexport function isNumber(o) {\n return typeof o === \"number\";\n}\n\nexport function isInteger(o) {\n return typeof o === \"number\" && o % 1 === 0;\n}\n\nexport function isString(o) {\n return typeof o === \"string\";\n}\n\nexport function isDate(o) {\n return Object.prototype.toString.call(o) === \"[object Date]\";\n}\n\n// CAPABILITIES\n\nexport function hasRelative() {\n try {\n return typeof Intl !== \"undefined\" && !!Intl.RelativeTimeFormat;\n } catch (e) {\n return false;\n }\n}\n\nexport function hasLocaleWeekInfo() {\n try {\n return (\n typeof Intl !== \"undefined\" &&\n !!Intl.Locale &&\n (\"weekInfo\" in Intl.Locale.prototype || \"getWeekInfo\" in Intl.Locale.prototype)\n );\n } catch (e) {\n return false;\n }\n}\n\n// OBJECTS AND ARRAYS\n\nexport function maybeArray(thing) {\n return Array.isArray(thing) ? thing : [thing];\n}\n\nexport function bestBy(arr, by, compare) {\n if (arr.length === 0) {\n return undefined;\n }\n return arr.reduce((best, next) => {\n const pair = [by(next), next];\n if (!best) {\n return pair;\n } else if (compare(best[0], pair[0]) === best[0]) {\n return best;\n } else {\n return pair;\n }\n }, null)[1];\n}\n\nexport function pick(obj, keys) {\n return keys.reduce((a, k) => {\n a[k] = obj[k];\n return a;\n }, {});\n}\n\nexport function hasOwnProperty(obj, prop) {\n return Object.prototype.hasOwnProperty.call(obj, prop);\n}\n\nexport function validateWeekSettings(settings) {\n if (settings == null) {\n return null;\n } else if (typeof settings !== \"object\") {\n throw new InvalidArgumentError(\"Week settings must be an object\");\n } else {\n if (\n !integerBetween(settings.firstDay, 1, 7) ||\n !integerBetween(settings.minimalDays, 1, 7) ||\n !Array.isArray(settings.weekend) ||\n settings.weekend.some((v) => !integerBetween(v, 1, 7))\n ) {\n throw new InvalidArgumentError(\"Invalid week settings\");\n }\n return {\n firstDay: settings.firstDay,\n minimalDays: settings.minimalDays,\n weekend: Array.from(settings.weekend),\n };\n }\n}\n\n// NUMBERS AND STRINGS\n\nexport function integerBetween(thing, bottom, top) {\n return isInteger(thing) && thing >= bottom && thing <= top;\n}\n\n// x % n but takes the sign of n instead of x\nexport function floorMod(x, n) {\n return x - n * Math.floor(x / n);\n}\n\nexport function padStart(input, n = 2) {\n const isNeg = input < 0;\n let padded;\n if (isNeg) {\n padded = \"-\" + (\"\" + -input).padStart(n, \"0\");\n } else {\n padded = (\"\" + input).padStart(n, \"0\");\n }\n return padded;\n}\n\nexport function parseInteger(string) {\n if (isUndefined(string) || string === null || string === \"\") {\n return undefined;\n } else {\n return parseInt(string, 10);\n }\n}\n\nexport function parseFloating(string) {\n if (isUndefined(string) || string === null || string === \"\") {\n return undefined;\n } else {\n return parseFloat(string);\n }\n}\n\nexport function parseMillis(fraction) {\n // Return undefined (instead of 0) in these cases, where fraction is not set\n if (isUndefined(fraction) || fraction === null || fraction === \"\") {\n return undefined;\n } else {\n const f = parseFloat(\"0.\" + fraction) * 1000;\n return Math.floor(f);\n }\n}\n\nexport function roundTo(number, digits, towardZero = false) {\n const factor = 10 ** digits,\n rounder = towardZero ? Math.trunc : Math.round;\n return rounder(number * factor) / factor;\n}\n\n// DATE BASICS\n\nexport function isLeapYear(year) {\n return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);\n}\n\nexport function daysInYear(year) {\n return isLeapYear(year) ? 366 : 365;\n}\n\nexport function daysInMonth(year, month) {\n const modMonth = floorMod(month - 1, 12) + 1,\n modYear = year + (month - modMonth) / 12;\n\n if (modMonth === 2) {\n return isLeapYear(modYear) ? 29 : 28;\n } else {\n return [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][modMonth - 1];\n }\n}\n\n// convert a calendar object to a local timestamp (epoch, but with the offset baked in)\nexport function objToLocalTS(obj) {\n let d = Date.UTC(\n obj.year,\n obj.month - 1,\n obj.day,\n obj.hour,\n obj.minute,\n obj.second,\n obj.millisecond\n );\n\n // for legacy reasons, years between 0 and 99 are interpreted as 19XX; revert that\n if (obj.year < 100 && obj.year >= 0) {\n d = new Date(d);\n // set the month and day again, this is necessary because year 2000 is a leap year, but year 100 is not\n // so if obj.year is in 99, but obj.day makes it roll over into year 100,\n // the calculations done by Date.UTC are using year 2000 - which is incorrect\n d.setUTCFullYear(obj.year, obj.month - 1, obj.day);\n }\n return +d;\n}\n\n// adapted from moment.js: https://github.com/moment/moment/blob/000ac1800e620f770f4eb31b5ae908f6167b0ab2/src/lib/units/week-calendar-utils.js\nfunction firstWeekOffset(year, minDaysInFirstWeek, startOfWeek) {\n const fwdlw = isoWeekdayToLocal(dayOfWeek(year, 1, minDaysInFirstWeek), startOfWeek);\n return -fwdlw + minDaysInFirstWeek - 1;\n}\n\nexport function weeksInWeekYear(weekYear, minDaysInFirstWeek = 4, startOfWeek = 1) {\n const weekOffset = firstWeekOffset(weekYear, minDaysInFirstWeek, startOfWeek);\n const weekOffsetNext = firstWeekOffset(weekYear + 1, minDaysInFirstWeek, startOfWeek);\n return (daysInYear(weekYear) - weekOffset + weekOffsetNext) / 7;\n}\n\nexport function untruncateYear(year) {\n if (year > 99) {\n return year;\n } else return year > Settings.twoDigitCutoffYear ? 1900 + year : 2000 + year;\n}\n\n// PARSING\n\nexport function parseZoneInfo(ts, offsetFormat, locale, timeZone = null) {\n const date = new Date(ts),\n intlOpts = {\n hourCycle: \"h23\",\n year: \"numeric\",\n month: \"2-digit\",\n day: \"2-digit\",\n hour: \"2-digit\",\n minute: \"2-digit\",\n };\n\n if (timeZone) {\n intlOpts.timeZone = timeZone;\n }\n\n const modified = { timeZoneName: offsetFormat, ...intlOpts };\n\n const parsed = new Intl.DateTimeFormat(locale, modified)\n .formatToParts(date)\n .find((m) => m.type.toLowerCase() === \"timezonename\");\n return parsed ? parsed.value : null;\n}\n\n// signedOffset('-5', '30') -> -330\nexport function signedOffset(offHourStr, offMinuteStr) {\n let offHour = parseInt(offHourStr, 10);\n\n // don't || this because we want to preserve -0\n if (Number.isNaN(offHour)) {\n offHour = 0;\n }\n\n const offMin = parseInt(offMinuteStr, 10) || 0,\n offMinSigned = offHour < 0 || Object.is(offHour, -0) ? -offMin : offMin;\n return offHour * 60 + offMinSigned;\n}\n\n// COERCION\n\nexport function asNumber(value) {\n const numericValue = Number(value);\n if (typeof value === \"boolean\" || value === \"\" || Number.isNaN(numericValue))\n throw new InvalidArgumentError(`Invalid unit value ${value}`);\n return numericValue;\n}\n\nexport function normalizeObject(obj, normalizer) {\n const normalized = {};\n for (const u in obj) {\n if (hasOwnProperty(obj, u)) {\n const v = obj[u];\n if (v === undefined || v === null) continue;\n normalized[normalizer(u)] = asNumber(v);\n }\n }\n return normalized;\n}\n\n/**\n * Returns the offset's value as a string\n * @param {number} ts - Epoch milliseconds for which to get the offset\n * @param {string} format - What style of offset to return.\n * Accepts 'narrow', 'short', or 'techie'. Returning '+6', '+06:00', or '+0600' respectively\n * @return {string}\n */\nexport function formatOffset(offset, format) {\n const hours = Math.trunc(Math.abs(offset / 60)),\n minutes = Math.trunc(Math.abs(offset % 60)),\n sign = offset >= 0 ? \"+\" : \"-\";\n\n switch (format) {\n case \"short\":\n return `${sign}${padStart(hours, 2)}:${padStart(minutes, 2)}`;\n case \"narrow\":\n return `${sign}${hours}${minutes > 0 ? `:${minutes}` : \"\"}`;\n case \"techie\":\n return `${sign}${padStart(hours, 2)}${padStart(minutes, 2)}`;\n default:\n throw new RangeError(`Value format ${format} is out of range for property format`);\n }\n}\n\nexport function timeObject(obj) {\n return pick(obj, [\"hour\", \"minute\", \"second\", \"millisecond\"]);\n}\n", "import * as Formats from \"./formats.js\";\nimport { pick } from \"./util.js\";\n\nfunction stringify(obj) {\n return JSON.stringify(obj, Object.keys(obj).sort());\n}\n\n/**\n * @private\n */\n\nexport const monthsLong = [\n \"January\",\n \"February\",\n \"March\",\n \"April\",\n \"May\",\n \"June\",\n \"July\",\n \"August\",\n \"September\",\n \"October\",\n \"November\",\n \"December\",\n];\n\nexport const monthsShort = [\n \"Jan\",\n \"Feb\",\n \"Mar\",\n \"Apr\",\n \"May\",\n \"Jun\",\n \"Jul\",\n \"Aug\",\n \"Sep\",\n \"Oct\",\n \"Nov\",\n \"Dec\",\n];\n\nexport const monthsNarrow = [\"J\", \"F\", \"M\", \"A\", \"M\", \"J\", \"J\", \"A\", \"S\", \"O\", \"N\", \"D\"];\n\nexport function months(length) {\n switch (length) {\n case \"narrow\":\n return [...monthsNarrow];\n case \"short\":\n return [...monthsShort];\n case \"long\":\n return [...monthsLong];\n case \"numeric\":\n return [\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"11\", \"12\"];\n case \"2-digit\":\n return [\"01\", \"02\", \"03\", \"04\", \"05\", \"06\", \"07\", \"08\", \"09\", \"10\", \"11\", \"12\"];\n default:\n return null;\n }\n}\n\nexport const weekdaysLong = [\n \"Monday\",\n \"Tuesday\",\n \"Wednesday\",\n \"Thursday\",\n \"Friday\",\n \"Saturday\",\n \"Sunday\",\n];\n\nexport const weekdaysShort = [\"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\", \"Sun\"];\n\nexport const weekdaysNarrow = [\"M\", \"T\", \"W\", \"T\", \"F\", \"S\", \"S\"];\n\nexport function weekdays(length) {\n switch (length) {\n case \"narrow\":\n return [...weekdaysNarrow];\n case \"short\":\n return [...weekdaysShort];\n case \"long\":\n return [...weekdaysLong];\n case \"numeric\":\n return [\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\"];\n default:\n return null;\n }\n}\n\nexport const meridiems = [\"AM\", \"PM\"];\n\nexport const erasLong = [\"Before Christ\", \"Anno Domini\"];\n\nexport const erasShort = [\"BC\", \"AD\"];\n\nexport const erasNarrow = [\"B\", \"A\"];\n\nexport function eras(length) {\n switch (length) {\n case \"narrow\":\n return [...erasNarrow];\n case \"short\":\n return [...erasShort];\n case \"long\":\n return [...erasLong];\n default:\n return null;\n }\n}\n\nexport function meridiemForDateTime(dt) {\n return meridiems[dt.hour < 12 ? 0 : 1];\n}\n\nexport function weekdayForDateTime(dt, length) {\n return weekdays(length)[dt.weekday - 1];\n}\n\nexport function monthForDateTime(dt, length) {\n return months(length)[dt.month - 1];\n}\n\nexport function eraForDateTime(dt, length) {\n return eras(length)[dt.year < 0 ? 0 : 1];\n}\n\nexport function formatRelativeTime(unit, count, numeric = \"always\", narrow = false) {\n const units = {\n years: [\"year\", \"yr.\"],\n quarters: [\"quarter\", \"qtr.\"],\n months: [\"month\", \"mo.\"],\n weeks: [\"week\", \"wk.\"],\n days: [\"day\", \"day\", \"days\"],\n hours: [\"hour\", \"hr.\"],\n minutes: [\"minute\", \"min.\"],\n seconds: [\"second\", \"sec.\"],\n };\n\n const lastable = [\"hours\", \"minutes\", \"seconds\"].indexOf(unit) === -1;\n\n if (numeric === \"auto\" && lastable) {\n const isDay = unit === \"days\";\n switch (count) {\n case 1:\n return isDay ? \"tomorrow\" : `next ${units[unit][0]}`;\n case -1:\n return isDay ? \"yesterday\" : `last ${units[unit][0]}`;\n case 0:\n return isDay ? \"today\" : `this ${units[unit][0]}`;\n default: // fall through\n }\n }\n\n const isInPast = Object.is(count, -0) || count < 0,\n fmtValue = Math.abs(count),\n singular = fmtValue === 1,\n lilUnits = units[unit],\n fmtUnit = narrow\n ? singular\n ? lilUnits[1]\n : lilUnits[2] || lilUnits[1]\n : singular\n ? units[unit][0]\n : unit;\n return isInPast ? `${fmtValue} ${fmtUnit} ago` : `in ${fmtValue} ${fmtUnit}`;\n}\n\nexport function formatString(knownFormat) {\n // these all have the offsets removed because we don't have access to them\n // without all the intl stuff this is backfilling\n const filtered = pick(knownFormat, [\n \"weekday\",\n \"era\",\n \"year\",\n \"month\",\n \"day\",\n \"hour\",\n \"minute\",\n \"second\",\n \"timeZoneName\",\n \"hourCycle\",\n ]),\n key = stringify(filtered),\n dateTimeHuge = \"EEEE, LLLL d, yyyy, h:mm a\";\n switch (key) {\n case stringify(Formats.DATE_SHORT):\n return \"M/d/yyyy\";\n case stringify(Formats.DATE_MED):\n return \"LLL d, yyyy\";\n case stringify(Formats.DATE_MED_WITH_WEEKDAY):\n return \"EEE, LLL d, yyyy\";\n case stringify(Formats.DATE_FULL):\n return \"LLLL d, yyyy\";\n case stringify(Formats.DATE_HUGE):\n return \"EEEE, LLLL d, yyyy\";\n case stringify(Formats.TIME_SIMPLE):\n return \"h:mm a\";\n case stringify(Formats.TIME_WITH_SECONDS):\n return \"h:mm:ss a\";\n case stringify(Formats.TIME_WITH_SHORT_OFFSET):\n return \"h:mm a\";\n case stringify(Formats.TIME_WITH_LONG_OFFSET):\n return \"h:mm a\";\n case stringify(Formats.TIME_24_SIMPLE):\n return \"HH:mm\";\n case stringify(Formats.TIME_24_WITH_SECONDS):\n return \"HH:mm:ss\";\n case stringify(Formats.TIME_24_WITH_SHORT_OFFSET):\n return \"HH:mm\";\n case stringify(Formats.TIME_24_WITH_LONG_OFFSET):\n return \"HH:mm\";\n case stringify(Formats.DATETIME_SHORT):\n return \"M/d/yyyy, h:mm a\";\n case stringify(Formats.DATETIME_MED):\n return \"LLL d, yyyy, h:mm a\";\n case stringify(Formats.DATETIME_FULL):\n return \"LLLL d, yyyy, h:mm a\";\n case stringify(Formats.DATETIME_HUGE):\n return dateTimeHuge;\n case stringify(Formats.DATETIME_SHORT_WITH_SECONDS):\n return \"M/d/yyyy, h:mm:ss a\";\n case stringify(Formats.DATETIME_MED_WITH_SECONDS):\n return \"LLL d, yyyy, h:mm:ss a\";\n case stringify(Formats.DATETIME_MED_WITH_WEEKDAY):\n return \"EEE, d LLL yyyy, h:mm a\";\n case stringify(Formats.DATETIME_FULL_WITH_SECONDS):\n return \"LLLL d, yyyy, h:mm:ss a\";\n case stringify(Formats.DATETIME_HUGE_WITH_SECONDS):\n return \"EEEE, LLLL d, yyyy, h:mm:ss a\";\n default:\n return dateTimeHuge;\n }\n}\n", "import * as English from \"./english.js\";\nimport * as Formats from \"./formats.js\";\nimport { padStart } from \"./util.js\";\n\nfunction stringifyTokens(splits, tokenToString) {\n let s = \"\";\n for (const token of splits) {\n if (token.literal) {\n s += token.val;\n } else {\n s += tokenToString(token.val);\n }\n }\n return s;\n}\n\nconst macroTokenToFormatOpts = {\n D: Formats.DATE_SHORT,\n DD: Formats.DATE_MED,\n DDD: Formats.DATE_FULL,\n DDDD: Formats.DATE_HUGE,\n t: Formats.TIME_SIMPLE,\n tt: Formats.TIME_WITH_SECONDS,\n ttt: Formats.TIME_WITH_SHORT_OFFSET,\n tttt: Formats.TIME_WITH_LONG_OFFSET,\n T: Formats.TIME_24_SIMPLE,\n TT: Formats.TIME_24_WITH_SECONDS,\n TTT: Formats.TIME_24_WITH_SHORT_OFFSET,\n TTTT: Formats.TIME_24_WITH_LONG_OFFSET,\n f: Formats.DATETIME_SHORT,\n ff: Formats.DATETIME_MED,\n fff: Formats.DATETIME_FULL,\n ffff: Formats.DATETIME_HUGE,\n F: Formats.DATETIME_SHORT_WITH_SECONDS,\n FF: Formats.DATETIME_MED_WITH_SECONDS,\n FFF: Formats.DATETIME_FULL_WITH_SECONDS,\n FFFF: Formats.DATETIME_HUGE_WITH_SECONDS,\n};\n\n/**\n * @private\n */\n\nexport default class Formatter {\n static create(locale, opts = {}) {\n return new Formatter(locale, opts);\n }\n\n static parseFormat(fmt) {\n // white-space is always considered a literal in user-provided formats\n // the \" \" token has a special meaning (see unitForToken)\n\n let current = null,\n currentFull = \"\",\n bracketed = false;\n const splits = [];\n for (let i = 0; i < fmt.length; i++) {\n const c = fmt.charAt(i);\n if (c === \"'\") {\n if (currentFull.length > 0) {\n splits.push({ literal: bracketed || /^\\s+$/.test(currentFull), val: currentFull });\n }\n current = null;\n currentFull = \"\";\n bracketed = !bracketed;\n } else if (bracketed) {\n currentFull += c;\n } else if (c === current) {\n currentFull += c;\n } else {\n if (currentFull.length > 0) {\n splits.push({ literal: /^\\s+$/.test(currentFull), val: currentFull });\n }\n currentFull = c;\n current = c;\n }\n }\n\n if (currentFull.length > 0) {\n splits.push({ literal: bracketed || /^\\s+$/.test(currentFull), val: currentFull });\n }\n\n return splits;\n }\n\n static macroTokenToFormatOpts(token) {\n return macroTokenToFormatOpts[token];\n }\n\n constructor(locale, formatOpts) {\n this.opts = formatOpts;\n this.loc = locale;\n this.systemLoc = null;\n }\n\n formatWithSystemDefault(dt, opts) {\n if (this.systemLoc === null) {\n this.systemLoc = this.loc.redefaultToSystem();\n }\n const df = this.systemLoc.dtFormatter(dt, { ...this.opts, ...opts });\n return df.format();\n }\n\n dtFormatter(dt, opts = {}) {\n return this.loc.dtFormatter(dt, { ...this.opts, ...opts });\n }\n\n formatDateTime(dt, opts) {\n return this.dtFormatter(dt, opts).format();\n }\n\n formatDateTimeParts(dt, opts) {\n return this.dtFormatter(dt, opts).formatToParts();\n }\n\n formatInterval(interval, opts) {\n const df = this.dtFormatter(interval.start, opts);\n return df.dtf.formatRange(interval.start.toJSDate(), interval.end.toJSDate());\n }\n\n resolvedOptions(dt, opts) {\n return this.dtFormatter(dt, opts).resolvedOptions();\n }\n\n num(n, p = 0) {\n // we get some perf out of doing this here, annoyingly\n if (this.opts.forceSimple) {\n return padStart(n, p);\n }\n\n const opts = { ...this.opts };\n\n if (p > 0) {\n opts.padTo = p;\n }\n\n return this.loc.numberFormatter(opts).format(n);\n }\n\n formatDateTimeFromString(dt, fmt) {\n const knownEnglish = this.loc.listingMode() === \"en\",\n useDateTimeFormatter = this.loc.outputCalendar && this.loc.outputCalendar !== \"gregory\",\n string = (opts, extract) => this.loc.extract(dt, opts, extract),\n formatOffset = (opts) => {\n if (dt.isOffsetFixed && dt.offset === 0 && opts.allowZ) {\n return \"Z\";\n }\n\n return dt.isValid ? dt.zone.formatOffset(dt.ts, opts.format) : \"\";\n },\n meridiem = () =>\n knownEnglish\n ? English.meridiemForDateTime(dt)\n : string({ hour: \"numeric\", hourCycle: \"h12\" }, \"dayperiod\"),\n month = (length, standalone) =>\n knownEnglish\n ? English.monthForDateTime(dt, length)\n : string(standalone ? { month: length } : { month: length, day: \"numeric\" }, \"month\"),\n weekday = (length, standalone) =>\n knownEnglish\n ? English.weekdayForDateTime(dt, length)\n : string(\n standalone ? { weekday: length } : { weekday: length, month: \"long\", day: \"numeric\" },\n \"weekday\"\n ),\n maybeMacro = (token) => {\n const formatOpts = Formatter.macroTokenToFormatOpts(token);\n if (formatOpts) {\n return this.formatWithSystemDefault(dt, formatOpts);\n } else {\n return token;\n }\n },\n era = (length) =>\n knownEnglish ? English.eraForDateTime(dt, length) : string({ era: length }, \"era\"),\n tokenToString = (token) => {\n // Where possible: https://cldr.unicode.org/translation/date-time/date-time-symbols\n switch (token) {\n // ms\n case \"S\":\n return this.num(dt.millisecond);\n case \"u\":\n // falls through\n case \"SSS\":\n return this.num(dt.millisecond, 3);\n // seconds\n case \"s\":\n return this.num(dt.second);\n case \"ss\":\n return this.num(dt.second, 2);\n // fractional seconds\n case \"uu\":\n return this.num(Math.floor(dt.millisecond / 10), 2);\n case \"uuu\":\n return this.num(Math.floor(dt.millisecond / 100));\n // minutes\n case \"m\":\n return this.num(dt.minute);\n case \"mm\":\n return this.num(dt.minute, 2);\n // hours\n case \"h\":\n return this.num(dt.hour % 12 === 0 ? 12 : dt.hour % 12);\n case \"hh\":\n return this.num(dt.hour % 12 === 0 ? 12 : dt.hour % 12, 2);\n case \"H\":\n return this.num(dt.hour);\n case \"HH\":\n return this.num(dt.hour, 2);\n // offset\n case \"Z\":\n // like +6\n return formatOffset({ format: \"narrow\", allowZ: this.opts.allowZ });\n case \"ZZ\":\n // like +06:00\n return formatOffset({ format: \"short\", allowZ: this.opts.allowZ });\n case \"ZZZ\":\n // like +0600\n return formatOffset({ format: \"techie\", allowZ: this.opts.allowZ });\n case \"ZZZZ\":\n // like EST\n return dt.zone.offsetName(dt.ts, { format: \"short\", locale: this.loc.locale });\n case \"ZZZZZ\":\n // like Eastern Standard Time\n return dt.zone.offsetName(dt.ts, { format: \"long\", locale: this.loc.locale });\n // zone\n case \"z\":\n // like America/New_York\n return dt.zoneName;\n // meridiems\n case \"a\":\n return meridiem();\n // dates\n case \"d\":\n return useDateTimeFormatter ? string({ day: \"numeric\" }, \"day\") : this.num(dt.day);\n case \"dd\":\n return useDateTimeFormatter ? string({ day: \"2-digit\" }, \"day\") : this.num(dt.day, 2);\n // weekdays - standalone\n case \"c\":\n // like 1\n return this.num(dt.weekday);\n case \"ccc\":\n // like 'Tues'\n return weekday(\"short\", true);\n case \"cccc\":\n // like 'Tuesday'\n return weekday(\"long\", true);\n case \"ccccc\":\n // like 'T'\n return weekday(\"narrow\", true);\n // weekdays - format\n case \"E\":\n // like 1\n return this.num(dt.weekday);\n case \"EEE\":\n // like 'Tues'\n return weekday(\"short\", false);\n case \"EEEE\":\n // like 'Tuesday'\n return weekday(\"long\", false);\n case \"EEEEE\":\n // like 'T'\n return weekday(\"narrow\", false);\n // months - standalone\n case \"L\":\n // like 1\n return useDateTimeFormatter\n ? string({ month: \"numeric\", day: \"numeric\" }, \"month\")\n : this.num(dt.month);\n case \"LL\":\n // like 01, doesn't seem to work\n return useDateTimeFormatter\n ? string({ month: \"2-digit\", day: \"numeric\" }, \"month\")\n : this.num(dt.month, 2);\n case \"LLL\":\n // like Jan\n return month(\"short\", true);\n case \"LLLL\":\n // like January\n return month(\"long\", true);\n case \"LLLLL\":\n // like J\n return month(\"narrow\", true);\n // months - format\n case \"M\":\n // like 1\n return useDateTimeFormatter\n ? string({ month: \"numeric\" }, \"month\")\n : this.num(dt.month);\n case \"MM\":\n // like 01\n return useDateTimeFormatter\n ? string({ month: \"2-digit\" }, \"month\")\n : this.num(dt.month, 2);\n case \"MMM\":\n // like Jan\n return month(\"short\", false);\n case \"MMMM\":\n // like January\n return month(\"long\", false);\n case \"MMMMM\":\n // like J\n return month(\"narrow\", false);\n // years\n case \"y\":\n // like 2014\n return useDateTimeFormatter ? string({ year: \"numeric\" }, \"year\") : this.num(dt.year);\n case \"yy\":\n // like 14\n return useDateTimeFormatter\n ? string({ year: \"2-digit\" }, \"year\")\n : this.num(dt.year.toString().slice(-2), 2);\n case \"yyyy\":\n // like 0012\n return useDateTimeFormatter\n ? string({ year: \"numeric\" }, \"year\")\n : this.num(dt.year, 4);\n case \"yyyyyy\":\n // like 000012\n return useDateTimeFormatter\n ? string({ year: \"numeric\" }, \"year\")\n : this.num(dt.year, 6);\n // eras\n case \"G\":\n // like AD\n return era(\"short\");\n case \"GG\":\n // like Anno Domini\n return era(\"long\");\n case \"GGGGG\":\n return era(\"narrow\");\n case \"kk\":\n return this.num(dt.weekYear.toString().slice(-2), 2);\n case \"kkkk\":\n return this.num(dt.weekYear, 4);\n case \"W\":\n return this.num(dt.weekNumber);\n case \"WW\":\n return this.num(dt.weekNumber, 2);\n case \"n\":\n return this.num(dt.localWeekNumber);\n case \"nn\":\n return this.num(dt.localWeekNumber, 2);\n case \"ii\":\n return this.num(dt.localWeekYear.toString().slice(-2), 2);\n case \"iiii\":\n return this.num(dt.localWeekYear, 4);\n case \"o\":\n return this.num(dt.ordinal);\n case \"ooo\":\n return this.num(dt.ordinal, 3);\n case \"q\":\n // like 1\n return this.num(dt.quarter);\n case \"qq\":\n // like 01\n return this.num(dt.quarter, 2);\n case \"X\":\n return this.num(Math.floor(dt.ts / 1000));\n case \"x\":\n return this.num(dt.ts);\n default:\n return maybeMacro(token);\n }\n };\n\n return stringifyTokens(Formatter.parseFormat(fmt), tokenToString);\n }\n\n formatDurationFromString(dur, fmt) {\n const tokenToField = (token) => {\n switch (token[0]) {\n case \"S\":\n return \"millisecond\";\n case \"s\":\n return \"second\";\n case \"m\":\n return \"minute\";\n case \"h\":\n return \"hour\";\n case \"d\":\n return \"day\";\n case \"w\":\n return \"week\";\n case \"M\":\n return \"month\";\n case \"y\":\n return \"year\";\n default:\n return null;\n }\n },\n tokenToString = (lildur) => (token) => {\n const mapped = tokenToField(token);\n if (mapped) {\n return this.num(lildur.get(mapped), token.length);\n } else {\n return token;\n }\n },\n tokens = Formatter.parseFormat(fmt),\n realTokens = tokens.reduce(\n (found, { literal, val }) => (literal ? found : found.concat(val)),\n []\n ),\n collapsed = dur.shiftTo(...realTokens.map(tokenToField).filter((t) => t));\n return stringifyTokens(tokens, tokenToString(collapsed));\n }\n}\n", "import {\n untruncateYear,\n signedOffset,\n parseInteger,\n parseMillis,\n isUndefined,\n parseFloating,\n} from \"./util.js\";\nimport * as English from \"./english.js\";\nimport FixedOffsetZone from \"../zones/fixedOffsetZone.js\";\nimport IANAZone from \"../zones/IANAZone.js\";\n\n/*\n * This file handles parsing for well-specified formats. Here's how it works:\n * Two things go into parsing: a regex to match with and an extractor to take apart the groups in the match.\n * An extractor is just a function that takes a regex match array and returns a { year: ..., month: ... } object\n * parse() does the work of executing the regex and applying the extractor. It takes multiple regex/extractor pairs to try in sequence.\n * Extractors can take a \"cursor\" representing the offset in the match to look at. This makes it easy to combine extractors.\n * combineExtractors() does the work of combining them, keeping track of the cursor through multiple extractions.\n * Some extractions are super dumb and simpleParse and fromStrings help DRY them.\n */\n\nconst ianaRegex = /[A-Za-z_+-]{1,256}(?::?\\/[A-Za-z0-9_+-]{1,256}(?:\\/[A-Za-z0-9_+-]{1,256})?)?/;\n\nfunction combineRegexes(...regexes) {\n const full = regexes.reduce((f, r) => f + r.source, \"\");\n return RegExp(`^${full}$`);\n}\n\nfunction combineExtractors(...extractors) {\n return (m) =>\n extractors\n .reduce(\n ([mergedVals, mergedZone, cursor], ex) => {\n const [val, zone, next] = ex(m, cursor);\n return [{ ...mergedVals, ...val }, zone || mergedZone, next];\n },\n [{}, null, 1]\n )\n .slice(0, 2);\n}\n\nfunction parse(s, ...patterns) {\n if (s == null) {\n return [null, null];\n }\n\n for (const [regex, extractor] of patterns) {\n const m = regex.exec(s);\n if (m) {\n return extractor(m);\n }\n }\n return [null, null];\n}\n\nfunction simpleParse(...keys) {\n return (match, cursor) => {\n const ret = {};\n let i;\n\n for (i = 0; i < keys.length; i++) {\n ret[keys[i]] = parseInteger(match[cursor + i]);\n }\n return [ret, null, cursor + i];\n };\n}\n\n// ISO and SQL parsing\nconst offsetRegex = /(?:(Z)|([+-]\\d\\d)(?::?(\\d\\d))?)/;\nconst isoExtendedZone = `(?:${offsetRegex.source}?(?:\\\\[(${ianaRegex.source})\\\\])?)?`;\nconst isoTimeBaseRegex = /(\\d\\d)(?::?(\\d\\d)(?::?(\\d\\d)(?:[.,](\\d{1,30}))?)?)?/;\nconst isoTimeRegex = RegExp(`${isoTimeBaseRegex.source}${isoExtendedZone}`);\nconst isoTimeExtensionRegex = RegExp(`(?:T${isoTimeRegex.source})?`);\nconst isoYmdRegex = /([+-]\\d{6}|\\d{4})(?:-?(\\d\\d)(?:-?(\\d\\d))?)?/;\nconst isoWeekRegex = /(\\d{4})-?W(\\d\\d)(?:-?(\\d))?/;\nconst isoOrdinalRegex = /(\\d{4})-?(\\d{3})/;\nconst extractISOWeekData = simpleParse(\"weekYear\", \"weekNumber\", \"weekDay\");\nconst extractISOOrdinalData = simpleParse(\"year\", \"ordinal\");\nconst sqlYmdRegex = /(\\d{4})-(\\d\\d)-(\\d\\d)/; // dumbed-down version of the ISO one\nconst sqlTimeRegex = RegExp(\n `${isoTimeBaseRegex.source} ?(?:${offsetRegex.source}|(${ianaRegex.source}))?`\n);\nconst sqlTimeExtensionRegex = RegExp(`(?: ${sqlTimeRegex.source})?`);\n\nfunction int(match, pos, fallback) {\n const m = match[pos];\n return isUndefined(m) ? fallback : parseInteger(m);\n}\n\nfunction extractISOYmd(match, cursor) {\n const item = {\n year: int(match, cursor),\n month: int(match, cursor + 1, 1),\n day: int(match, cursor + 2, 1),\n };\n\n return [item, null, cursor + 3];\n}\n\nfunction extractISOTime(match, cursor) {\n const item = {\n hours: int(match, cursor, 0),\n minutes: int(match, cursor + 1, 0),\n seconds: int(match, cursor + 2, 0),\n milliseconds: parseMillis(match[cursor + 3]),\n };\n\n return [item, null, cursor + 4];\n}\n\nfunction extractISOOffset(match, cursor) {\n const local = !match[cursor] && !match[cursor + 1],\n fullOffset = signedOffset(match[cursor + 1], match[cursor + 2]),\n zone = local ? null : FixedOffsetZone.instance(fullOffset);\n return [{}, zone, cursor + 3];\n}\n\nfunction extractIANAZone(match, cursor) {\n const zone = match[cursor] ? IANAZone.create(match[cursor]) : null;\n return [{}, zone, cursor + 1];\n}\n\n// ISO time parsing\n\nconst isoTimeOnly = RegExp(`^T?${isoTimeBaseRegex.source}$`);\n\n// ISO duration parsing\n\nconst isoDuration =\n /^-?P(?:(?:(-?\\d{1,20}(?:\\.\\d{1,20})?)Y)?(?:(-?\\d{1,20}(?:\\.\\d{1,20})?)M)?(?:(-?\\d{1,20}(?:\\.\\d{1,20})?)W)?(?:(-?\\d{1,20}(?:\\.\\d{1,20})?)D)?(?:T(?:(-?\\d{1,20}(?:\\.\\d{1,20})?)H)?(?:(-?\\d{1,20}(?:\\.\\d{1,20})?)M)?(?:(-?\\d{1,20})(?:[.,](-?\\d{1,20}))?S)?)?)$/;\n\nfunction extractISODuration(match) {\n const [s, yearStr, monthStr, weekStr, dayStr, hourStr, minuteStr, secondStr, millisecondsStr] =\n match;\n\n const hasNegativePrefix = s[0] === \"-\";\n const negativeSeconds = secondStr && secondStr[0] === \"-\";\n\n const maybeNegate = (num, force = false) =>\n num !== undefined && (force || (num && hasNegativePrefix)) ? -num : num;\n\n return [\n {\n years: maybeNegate(parseFloating(yearStr)),\n months: maybeNegate(parseFloating(monthStr)),\n weeks: maybeNegate(parseFloating(weekStr)),\n days: maybeNegate(parseFloating(dayStr)),\n hours: maybeNegate(parseFloating(hourStr)),\n minutes: maybeNegate(parseFloating(minuteStr)),\n seconds: maybeNegate(parseFloating(secondStr), secondStr === \"-0\"),\n milliseconds: maybeNegate(parseMillis(millisecondsStr), negativeSeconds),\n },\n ];\n}\n\n// These are a little braindead. EDT *should* tell us that we're in, say, America/New_York\n// and not just that we're in -240 *right now*. But since I don't think these are used that often\n// I'm just going to ignore that\nconst obsOffsets = {\n GMT: 0,\n EDT: -4 * 60,\n EST: -5 * 60,\n CDT: -5 * 60,\n CST: -6 * 60,\n MDT: -6 * 60,\n MST: -7 * 60,\n PDT: -7 * 60,\n PST: -8 * 60,\n};\n\nfunction fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr) {\n const result = {\n year: yearStr.length === 2 ? untruncateYear(parseInteger(yearStr)) : parseInteger(yearStr),\n month: English.monthsShort.indexOf(monthStr) + 1,\n day: parseInteger(dayStr),\n hour: parseInteger(hourStr),\n minute: parseInteger(minuteStr),\n };\n\n if (secondStr) result.second = parseInteger(secondStr);\n if (weekdayStr) {\n result.weekday =\n weekdayStr.length > 3\n ? English.weekdaysLong.indexOf(weekdayStr) + 1\n : English.weekdaysShort.indexOf(weekdayStr) + 1;\n }\n\n return result;\n}\n\n// RFC 2822/5322\nconst rfc2822 =\n /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\\s)?(\\d{1,2})\\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\\s(\\d{2,4})\\s(\\d\\d):(\\d\\d)(?::(\\d\\d))?\\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\\d\\d)(\\d\\d)))$/;\n\nfunction extractRFC2822(match) {\n const [\n ,\n weekdayStr,\n dayStr,\n monthStr,\n yearStr,\n hourStr,\n minuteStr,\n secondStr,\n obsOffset,\n milOffset,\n offHourStr,\n offMinuteStr,\n ] = match,\n result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr);\n\n let offset;\n if (obsOffset) {\n offset = obsOffsets[obsOffset];\n } else if (milOffset) {\n offset = 0;\n } else {\n offset = signedOffset(offHourStr, offMinuteStr);\n }\n\n return [result, new FixedOffsetZone(offset)];\n}\n\nfunction preprocessRFC2822(s) {\n // Remove comments and folding whitespace and replace multiple-spaces with a single space\n return s\n .replace(/\\([^()]*\\)|[\\n\\t]/g, \" \")\n .replace(/(\\s\\s+)/g, \" \")\n .trim();\n}\n\n// http date\n\nconst rfc1123 =\n /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\\d\\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\\d{4}) (\\d\\d):(\\d\\d):(\\d\\d) GMT$/,\n rfc850 =\n /^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\\d\\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\\d\\d) (\\d\\d):(\\d\\d):(\\d\\d) GMT$/,\n ascii =\n /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \\d|\\d\\d) (\\d\\d):(\\d\\d):(\\d\\d) (\\d{4})$/;\n\nfunction extractRFC1123Or850(match) {\n const [, weekdayStr, dayStr, monthStr, yearStr, hourStr, minuteStr, secondStr] = match,\n result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr);\n return [result, FixedOffsetZone.utcInstance];\n}\n\nfunction extractASCII(match) {\n const [, weekdayStr, monthStr, dayStr, hourStr, minuteStr, secondStr, yearStr] = match,\n result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr);\n return [result, FixedOffsetZone.utcInstance];\n}\n\nconst isoYmdWithTimeExtensionRegex = combineRegexes(isoYmdRegex, isoTimeExtensionRegex);\nconst isoWeekWithTimeExtensionRegex = combineRegexes(isoWeekRegex, isoTimeExtensionRegex);\nconst isoOrdinalWithTimeExtensionRegex = combineRegexes(isoOrdinalRegex, isoTimeExtensionRegex);\nconst isoTimeCombinedRegex = combineRegexes(isoTimeRegex);\n\nconst extractISOYmdTimeAndOffset = combineExtractors(\n extractISOYmd,\n extractISOTime,\n extractISOOffset,\n extractIANAZone\n);\nconst extractISOWeekTimeAndOffset = combineExtractors(\n extractISOWeekData,\n extractISOTime,\n extractISOOffset,\n extractIANAZone\n);\nconst extractISOOrdinalDateAndTime = combineExtractors(\n extractISOOrdinalData,\n extractISOTime,\n extractISOOffset,\n extractIANAZone\n);\nconst extractISOTimeAndOffset = combineExtractors(\n extractISOTime,\n extractISOOffset,\n extractIANAZone\n);\n\n/*\n * @private\n */\n\nexport function parseISODate(s) {\n return parse(\n s,\n [isoYmdWithTimeExtensionRegex, extractISOYmdTimeAndOffset],\n [isoWeekWithTimeExtensionRegex, extractISOWeekTimeAndOffset],\n [isoOrdinalWithTimeExtensionRegex, extractISOOrdinalDateAndTime],\n [isoTimeCombinedRegex, extractISOTimeAndOffset]\n );\n}\n\nexport function parseRFC2822Date(s) {\n return parse(preprocessRFC2822(s), [rfc2822, extractRFC2822]);\n}\n\nexport function parseHTTPDate(s) {\n return parse(\n s,\n [rfc1123, extractRFC1123Or850],\n [rfc850, extractRFC1123Or850],\n [ascii, extractASCII]\n );\n}\n\nexport function parseISODuration(s) {\n return parse(s, [isoDuration, extractISODuration]);\n}\n\nconst extractISOTimeOnly = combineExtractors(extractISOTime);\n\nexport function parseISOTimeOnly(s) {\n return parse(s, [isoTimeOnly, extractISOTimeOnly]);\n}\n\nconst sqlYmdWithTimeExtensionRegex = combineRegexes(sqlYmdRegex, sqlTimeExtensionRegex);\nconst sqlTimeCombinedRegex = combineRegexes(sqlTimeRegex);\n\nconst extractISOTimeOffsetAndIANAZone = combineExtractors(\n extractISOTime,\n extractISOOffset,\n extractIANAZone\n);\n\nexport function parseSQL(s) {\n return parse(\n s,\n [sqlYmdWithTimeExtensionRegex, extractISOYmdTimeAndOffset],\n [sqlTimeCombinedRegex, extractISOTimeOffsetAndIANAZone]\n );\n}\n", "import { InvalidArgumentError, InvalidDurationError, InvalidUnitError } from \"./errors.js\";\nimport Formatter from \"./impl/formatter.js\";\nimport Invalid from \"./impl/invalid.js\";\nimport Locale from \"./impl/locale.js\";\nimport { parseISODuration, parseISOTimeOnly } from \"./impl/regexParser.js\";\nimport {\n asNumber,\n hasOwnProperty,\n isNumber,\n isUndefined,\n normalizeObject,\n roundTo,\n} from \"./impl/util.js\";\nimport Settings from \"./settings.js\";\nimport DateTime from \"./datetime.js\";\n\nconst INVALID = \"Invalid Duration\";\n\n// unit conversion constants\nexport const lowOrderMatrix = {\n weeks: {\n days: 7,\n hours: 7 * 24,\n minutes: 7 * 24 * 60,\n seconds: 7 * 24 * 60 * 60,\n milliseconds: 7 * 24 * 60 * 60 * 1000,\n },\n days: {\n hours: 24,\n minutes: 24 * 60,\n seconds: 24 * 60 * 60,\n milliseconds: 24 * 60 * 60 * 1000,\n },\n hours: { minutes: 60, seconds: 60 * 60, milliseconds: 60 * 60 * 1000 },\n minutes: { seconds: 60, milliseconds: 60 * 1000 },\n seconds: { milliseconds: 1000 },\n },\n casualMatrix = {\n years: {\n quarters: 4,\n months: 12,\n weeks: 52,\n days: 365,\n hours: 365 * 24,\n minutes: 365 * 24 * 60,\n seconds: 365 * 24 * 60 * 60,\n milliseconds: 365 * 24 * 60 * 60 * 1000,\n },\n quarters: {\n months: 3,\n weeks: 13,\n days: 91,\n hours: 91 * 24,\n minutes: 91 * 24 * 60,\n seconds: 91 * 24 * 60 * 60,\n milliseconds: 91 * 24 * 60 * 60 * 1000,\n },\n months: {\n weeks: 4,\n days: 30,\n hours: 30 * 24,\n minutes: 30 * 24 * 60,\n seconds: 30 * 24 * 60 * 60,\n milliseconds: 30 * 24 * 60 * 60 * 1000,\n },\n\n ...lowOrderMatrix,\n },\n daysInYearAccurate = 146097.0 / 400,\n daysInMonthAccurate = 146097.0 / 4800,\n accurateMatrix = {\n years: {\n quarters: 4,\n months: 12,\n weeks: daysInYearAccurate / 7,\n days: daysInYearAccurate,\n hours: daysInYearAccurate * 24,\n minutes: daysInYearAccurate * 24 * 60,\n seconds: daysInYearAccurate * 24 * 60 * 60,\n milliseconds: daysInYearAccurate * 24 * 60 * 60 * 1000,\n },\n quarters: {\n months: 3,\n weeks: daysInYearAccurate / 28,\n days: daysInYearAccurate / 4,\n hours: (daysInYearAccurate * 24) / 4,\n minutes: (daysInYearAccurate * 24 * 60) / 4,\n seconds: (daysInYearAccurate * 24 * 60 * 60) / 4,\n milliseconds: (daysInYearAccurate * 24 * 60 * 60 * 1000) / 4,\n },\n months: {\n weeks: daysInMonthAccurate / 7,\n days: daysInMonthAccurate,\n hours: daysInMonthAccurate * 24,\n minutes: daysInMonthAccurate * 24 * 60,\n seconds: daysInMonthAccurate * 24 * 60 * 60,\n milliseconds: daysInMonthAccurate * 24 * 60 * 60 * 1000,\n },\n ...lowOrderMatrix,\n };\n\n// units ordered by size\nconst orderedUnits = [\n \"years\",\n \"quarters\",\n \"months\",\n \"weeks\",\n \"days\",\n \"hours\",\n \"minutes\",\n \"seconds\",\n \"milliseconds\",\n];\n\nconst reverseUnits = orderedUnits.slice(0).reverse();\n\n// clone really means \"create another instance just like this one, but with these changes\"\nfunction clone(dur, alts, clear = false) {\n // deep merge for vals\n const conf = {\n values: clear ? alts.values : { ...dur.values, ...(alts.values || {}) },\n loc: dur.loc.clone(alts.loc),\n conversionAccuracy: alts.conversionAccuracy || dur.conversionAccuracy,\n matrix: alts.matrix || dur.matrix,\n };\n return new Duration(conf);\n}\n\nfunction durationToMillis(matrix, vals) {\n let sum = vals.milliseconds ?? 0;\n for (const unit of reverseUnits.slice(1)) {\n if (vals[unit]) {\n sum += vals[unit] * matrix[unit][\"milliseconds\"];\n }\n }\n return sum;\n}\n\n// NB: mutates parameters\nfunction normalizeValues(matrix, vals) {\n // the logic below assumes the overall value of the duration is positive\n // if this is not the case, factor is used to make it so\n const factor = durationToMillis(matrix, vals) < 0 ? -1 : 1;\n\n orderedUnits.reduceRight((previous, current) => {\n if (!isUndefined(vals[current])) {\n if (previous) {\n const previousVal = vals[previous] * factor;\n const conv = matrix[current][previous];\n\n // if (previousVal < 0):\n // lower order unit is negative (e.g. { years: 2, days: -2 })\n // normalize this by reducing the higher order unit by the appropriate amount\n // and increasing the lower order unit\n // this can never make the higher order unit negative, because this function only operates\n // on positive durations, so the amount of time represented by the lower order unit cannot\n // be larger than the higher order unit\n // else:\n // lower order unit is positive (e.g. { years: 2, days: 450 } or { years: -2, days: 450 })\n // in this case we attempt to convert as much as possible from the lower order unit into\n // the higher order one\n //\n // Math.floor takes care of both of these cases, rounding away from 0\n // if previousVal < 0 it makes the absolute value larger\n // if previousVal >= it makes the absolute value smaller\n const rollUp = Math.floor(previousVal / conv);\n vals[current] += rollUp * factor;\n vals[previous] -= rollUp * conv * factor;\n }\n return current;\n } else {\n return previous;\n }\n }, null);\n\n // try to convert any decimals into smaller units if possible\n // for example for { years: 2.5, days: 0, seconds: 0 } we want to get { years: 2, days: 182, hours: 12 }\n orderedUnits.reduce((previous, current) => {\n if (!isUndefined(vals[current])) {\n if (previous) {\n const fraction = vals[previous] % 1;\n vals[previous] -= fraction;\n vals[current] += fraction * matrix[previous][current];\n }\n return current;\n } else {\n return previous;\n }\n }, null);\n}\n\n// Remove all properties with a value of 0 from an object\nfunction removeZeroes(vals) {\n const newVals = {};\n for (const [key, value] of Object.entries(vals)) {\n if (value !== 0) {\n newVals[key] = value;\n }\n }\n return newVals;\n}\n\n/**\n * A Duration object represents a period of time, like \"2 months\" or \"1 day, 1 hour\". Conceptually, it's just a map of units to their quantities, accompanied by some additional configuration and methods for creating, parsing, interrogating, transforming, and formatting them. They can be used on their own or in conjunction with other Luxon types; for example, you can use {@link DateTime#plus} to add a Duration object to a DateTime, producing another DateTime.\n *\n * Here is a brief overview of commonly used methods and getters in Duration:\n *\n * * **Creation** To create a Duration, use {@link Duration.fromMillis}, {@link Duration.fromObject}, or {@link Duration.fromISO}.\n * * **Unit values** See the {@link Duration#years}, {@link Duration#months}, {@link Duration#weeks}, {@link Duration#days}, {@link Duration#hours}, {@link Duration#minutes}, {@link Duration#seconds}, {@link Duration#milliseconds} accessors.\n * * **Configuration** See {@link Duration#locale} and {@link Duration#numberingSystem} accessors.\n * * **Transformation** To create new Durations out of old ones use {@link Duration#plus}, {@link Duration#minus}, {@link Duration#normalize}, {@link Duration#set}, {@link Duration#reconfigure}, {@link Duration#shiftTo}, and {@link Duration#negate}.\n * * **Output** To convert the Duration into other representations, see {@link Duration#as}, {@link Duration#toISO}, {@link Duration#toFormat}, and {@link Duration#toJSON}\n *\n * There's are more methods documented below. In addition, for more information on subtler topics like internationalization and validity, see the external documentation.\n */\nexport default class Duration {\n /**\n * @private\n */\n constructor(config) {\n const accurate = config.conversionAccuracy === \"longterm\" || false;\n let matrix = accurate ? accurateMatrix : casualMatrix;\n\n if (config.matrix) {\n matrix = config.matrix;\n }\n\n /**\n * @access private\n */\n this.values = config.values;\n /**\n * @access private\n */\n this.loc = config.loc || Locale.create();\n /**\n * @access private\n */\n this.conversionAccuracy = accurate ? \"longterm\" : \"casual\";\n /**\n * @access private\n */\n this.invalid = config.invalid || null;\n /**\n * @access private\n */\n this.matrix = matrix;\n /**\n * @access private\n */\n this.isLuxonDuration = true;\n }\n\n /**\n * Create Duration from a number of milliseconds.\n * @param {number} count of milliseconds\n * @param {Object} opts - options for parsing\n * @param {string} [opts.locale='en-US'] - the locale to use\n * @param {string} opts.numberingSystem - the numbering system to use\n * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use\n * @return {Duration}\n */\n static fromMillis(count, opts) {\n return Duration.fromObject({ milliseconds: count }, opts);\n }\n\n /**\n * Create a Duration from a JavaScript object with keys like 'years' and 'hours'.\n * If this object is empty then a zero milliseconds duration is returned.\n * @param {Object} obj - the object to create the DateTime from\n * @param {number} obj.years\n * @param {number} obj.quarters\n * @param {number} obj.months\n * @param {number} obj.weeks\n * @param {number} obj.days\n * @param {number} obj.hours\n * @param {number} obj.minutes\n * @param {number} obj.seconds\n * @param {number} obj.milliseconds\n * @param {Object} [opts=[]] - options for creating this Duration\n * @param {string} [opts.locale='en-US'] - the locale to use\n * @param {string} opts.numberingSystem - the numbering system to use\n * @param {string} [opts.conversionAccuracy='casual'] - the preset conversion system to use\n * @param {string} [opts.matrix=Object] - the custom conversion system to use\n * @return {Duration}\n */\n static fromObject(obj, opts = {}) {\n if (obj == null || typeof obj !== \"object\") {\n throw new InvalidArgumentError(\n `Duration.fromObject: argument expected to be an object, got ${\n obj === null ? \"null\" : typeof obj\n }`\n );\n }\n\n return new Duration({\n values: normalizeObject(obj, Duration.normalizeUnit),\n loc: Locale.fromObject(opts),\n conversionAccuracy: opts.conversionAccuracy,\n matrix: opts.matrix,\n });\n }\n\n /**\n * Create a Duration from DurationLike.\n *\n * @param {Object | number | Duration} durationLike\n * One of:\n * - object with keys like 'years' and 'hours'.\n * - number representing milliseconds\n * - Duration instance\n * @return {Duration}\n */\n static fromDurationLike(durationLike) {\n if (isNumber(durationLike)) {\n return Duration.fromMillis(durationLike);\n } else if (Duration.isDuration(durationLike)) {\n return durationLike;\n } else if (typeof durationLike === \"object\") {\n return Duration.fromObject(durationLike);\n } else {\n throw new InvalidArgumentError(\n `Unknown duration argument ${durationLike} of type ${typeof durationLike}`\n );\n }\n }\n\n /**\n * Create a Duration from an ISO 8601 duration string.\n * @param {string} text - text to parse\n * @param {Object} opts - options for parsing\n * @param {string} [opts.locale='en-US'] - the locale to use\n * @param {string} opts.numberingSystem - the numbering system to use\n * @param {string} [opts.conversionAccuracy='casual'] - the preset conversion system to use\n * @param {string} [opts.matrix=Object] - the preset conversion system to use\n * @see https://en.wikipedia.org/wiki/ISO_8601#Durations\n * @example Duration.fromISO('P3Y6M1W4DT12H30M5S').toObject() //=> { years: 3, months: 6, weeks: 1, days: 4, hours: 12, minutes: 30, seconds: 5 }\n * @example Duration.fromISO('PT23H').toObject() //=> { hours: 23 }\n * @example Duration.fromISO('P5Y3M').toObject() //=> { years: 5, months: 3 }\n * @return {Duration}\n */\n static fromISO(text, opts) {\n const [parsed] = parseISODuration(text);\n if (parsed) {\n return Duration.fromObject(parsed, opts);\n } else {\n return Duration.invalid(\"unparsable\", `the input \"${text}\" can't be parsed as ISO 8601`);\n }\n }\n\n /**\n * Create a Duration from an ISO 8601 time string.\n * @param {string} text - text to parse\n * @param {Object} opts - options for parsing\n * @param {string} [opts.locale='en-US'] - the locale to use\n * @param {string} opts.numberingSystem - the numbering system to use\n * @param {string} [opts.conversionAccuracy='casual'] - the preset conversion system to use\n * @param {string} [opts.matrix=Object] - the conversion system to use\n * @see https://en.wikipedia.org/wiki/ISO_8601#Times\n * @example Duration.fromISOTime('11:22:33.444').toObject() //=> { hours: 11, minutes: 22, seconds: 33, milliseconds: 444 }\n * @example Duration.fromISOTime('11:00').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }\n * @example Duration.fromISOTime('T11:00').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }\n * @example Duration.fromISOTime('1100').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }\n * @example Duration.fromISOTime('T1100').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }\n * @return {Duration}\n */\n static fromISOTime(text, opts) {\n const [parsed] = parseISOTimeOnly(text);\n if (parsed) {\n return Duration.fromObject(parsed, opts);\n } else {\n return Duration.invalid(\"unparsable\", `the input \"${text}\" can't be parsed as ISO 8601`);\n }\n }\n\n /**\n * Create an invalid Duration.\n * @param {string} reason - simple string of why this datetime is invalid. Should not contain parameters or anything else data-dependent\n * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information\n * @return {Duration}\n */\n static invalid(reason, explanation = null) {\n if (!reason) {\n throw new InvalidArgumentError(\"need to specify a reason the Duration is invalid\");\n }\n\n const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation);\n\n if (Settings.throwOnInvalid) {\n throw new InvalidDurationError(invalid);\n } else {\n return new Duration({ invalid });\n }\n }\n\n /**\n * @private\n */\n static normalizeUnit(unit) {\n const normalized = {\n year: \"years\",\n years: \"years\",\n quarter: \"quarters\",\n quarters: \"quarters\",\n month: \"months\",\n months: \"months\",\n week: \"weeks\",\n weeks: \"weeks\",\n day: \"days\",\n days: \"days\",\n hour: \"hours\",\n hours: \"hours\",\n minute: \"minutes\",\n minutes: \"minutes\",\n second: \"seconds\",\n seconds: \"seconds\",\n millisecond: \"milliseconds\",\n milliseconds: \"milliseconds\",\n }[unit ? unit.toLowerCase() : unit];\n\n if (!normalized) throw new InvalidUnitError(unit);\n\n return normalized;\n }\n\n /**\n * Check if an object is a Duration. Works across context boundaries\n * @param {object} o\n * @return {boolean}\n */\n static isDuration(o) {\n return (o && o.isLuxonDuration) || false;\n }\n\n /**\n * Get the locale of a Duration, such 'en-GB'\n * @type {string}\n */\n get locale() {\n return this.isValid ? this.loc.locale : null;\n }\n\n /**\n * Get the numbering system of a Duration, such 'beng'. The numbering system is used when formatting the Duration\n *\n * @type {string}\n */\n get numberingSystem() {\n return this.isValid ? this.loc.numberingSystem : null;\n }\n\n /**\n * Returns a string representation of this Duration formatted according to the specified format string. You may use these tokens:\n * * `S` for milliseconds\n * * `s` for seconds\n * * `m` for minutes\n * * `h` for hours\n * * `d` for days\n * * `w` for weeks\n * * `M` for months\n * * `y` for years\n * Notes:\n * * Add padding by repeating the token, e.g. \"yy\" pads the years to two digits, \"hhhh\" pads the hours out to four digits\n * * Tokens can be escaped by wrapping with single quotes.\n * * The duration will be converted to the set of units in the format string using {@link Duration#shiftTo} and the Durations's conversion accuracy setting.\n * @param {string} fmt - the format string\n * @param {Object} opts - options\n * @param {boolean} [opts.floor=true] - floor numerical values\n * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat(\"y d s\") //=> \"1 6 2\"\n * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat(\"yy dd sss\") //=> \"01 06 002\"\n * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat(\"M S\") //=> \"12 518402000\"\n * @return {string}\n */\n toFormat(fmt, opts = {}) {\n // reverse-compat since 1.2; we always round down now, never up, and we do it by default\n const fmtOpts = {\n ...opts,\n floor: opts.round !== false && opts.floor !== false,\n };\n return this.isValid\n ? Formatter.create(this.loc, fmtOpts).formatDurationFromString(this, fmt)\n : INVALID;\n }\n\n /**\n * Returns a string representation of a Duration with all units included.\n * To modify its behavior, use `listStyle` and any Intl.NumberFormat option, though `unitDisplay` is especially relevant.\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#options\n * @param {Object} opts - Formatting options. Accepts the same keys as the options parameter of the native `Intl.NumberFormat` constructor, as well as `listStyle`.\n * @param {string} [opts.listStyle='narrow'] - How to format the merged list. Corresponds to the `style` property of the options parameter of the native `Intl.ListFormat` constructor.\n * @example\n * ```js\n * var dur = Duration.fromObject({ days: 1, hours: 5, minutes: 6 })\n * dur.toHuman() //=> '1 day, 5 hours, 6 minutes'\n * dur.toHuman({ listStyle: \"long\" }) //=> '1 day, 5 hours, and 6 minutes'\n * dur.toHuman({ unitDisplay: \"short\" }) //=> '1 day, 5 hr, 6 min'\n * ```\n */\n toHuman(opts = {}) {\n if (!this.isValid) return INVALID;\n\n const l = orderedUnits\n .map((unit) => {\n const val = this.values[unit];\n if (isUndefined(val)) {\n return null;\n }\n return this.loc\n .numberFormatter({ style: \"unit\", unitDisplay: \"long\", ...opts, unit: unit.slice(0, -1) })\n .format(val);\n })\n .filter((n) => n);\n\n return this.loc\n .listFormatter({ type: \"conjunction\", style: opts.listStyle || \"narrow\", ...opts })\n .format(l);\n }\n\n /**\n * Returns a JavaScript object with this Duration's values.\n * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toObject() //=> { years: 1, days: 6, seconds: 2 }\n * @return {Object}\n */\n toObject() {\n if (!this.isValid) return {};\n return { ...this.values };\n }\n\n /**\n * Returns an ISO 8601-compliant string representation of this Duration.\n * @see https://en.wikipedia.org/wiki/ISO_8601#Durations\n * @example Duration.fromObject({ years: 3, seconds: 45 }).toISO() //=> 'P3YT45S'\n * @example Duration.fromObject({ months: 4, seconds: 45 }).toISO() //=> 'P4MT45S'\n * @example Duration.fromObject({ months: 5 }).toISO() //=> 'P5M'\n * @example Duration.fromObject({ minutes: 5 }).toISO() //=> 'PT5M'\n * @example Duration.fromObject({ milliseconds: 6 }).toISO() //=> 'PT0.006S'\n * @return {string}\n */\n toISO() {\n // we could use the formatter, but this is an easier way to get the minimum string\n if (!this.isValid) return null;\n\n let s = \"P\";\n if (this.years !== 0) s += this.years + \"Y\";\n if (this.months !== 0 || this.quarters !== 0) s += this.months + this.quarters * 3 + \"M\";\n if (this.weeks !== 0) s += this.weeks + \"W\";\n if (this.days !== 0) s += this.days + \"D\";\n if (this.hours !== 0 || this.minutes !== 0 || this.seconds !== 0 || this.milliseconds !== 0)\n s += \"T\";\n if (this.hours !== 0) s += this.hours + \"H\";\n if (this.minutes !== 0) s += this.minutes + \"M\";\n if (this.seconds !== 0 || this.milliseconds !== 0)\n // this will handle \"floating point madness\" by removing extra decimal places\n // https://stackoverflow.com/questions/588004/is-floating-point-math-broken\n s += roundTo(this.seconds + this.milliseconds / 1000, 3) + \"S\";\n if (s === \"P\") s += \"T0S\";\n return s;\n }\n\n /**\n * Returns an ISO 8601-compliant string representation of this Duration, formatted as a time of day.\n * Note that this will return null if the duration is invalid, negative, or equal to or greater than 24 hours.\n * @see https://en.wikipedia.org/wiki/ISO_8601#Times\n * @param {Object} opts - options\n * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0\n * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0\n * @param {boolean} [opts.includePrefix=false] - include the `T` prefix\n * @param {string} [opts.format='extended'] - choose between the basic and extended format\n * @example Duration.fromObject({ hours: 11 }).toISOTime() //=> '11:00:00.000'\n * @example Duration.fromObject({ hours: 11 }).toISOTime({ suppressMilliseconds: true }) //=> '11:00:00'\n * @example Duration.fromObject({ hours: 11 }).toISOTime({ suppressSeconds: true }) //=> '11:00'\n * @example Duration.fromObject({ hours: 11 }).toISOTime({ includePrefix: true }) //=> 'T11:00:00.000'\n * @example Duration.fromObject({ hours: 11 }).toISOTime({ format: 'basic' }) //=> '110000.000'\n * @return {string}\n */\n toISOTime(opts = {}) {\n if (!this.isValid) return null;\n\n const millis = this.toMillis();\n if (millis < 0 || millis >= 86400000) return null;\n\n opts = {\n suppressMilliseconds: false,\n suppressSeconds: false,\n includePrefix: false,\n format: \"extended\",\n ...opts,\n includeOffset: false,\n };\n\n const dateTime = DateTime.fromMillis(millis, { zone: \"UTC\" });\n return dateTime.toISOTime(opts);\n }\n\n /**\n * Returns an ISO 8601 representation of this Duration appropriate for use in JSON.\n * @return {string}\n */\n toJSON() {\n return this.toISO();\n }\n\n /**\n * Returns an ISO 8601 representation of this Duration appropriate for use in debugging.\n * @return {string}\n */\n toString() {\n return this.toISO();\n }\n\n /**\n * Returns a string representation of this Duration appropriate for the REPL.\n * @return {string}\n */\n [Symbol.for(\"nodejs.util.inspect.custom\")]() {\n if (this.isValid) {\n return `Duration { values: ${JSON.stringify(this.values)} }`;\n } else {\n return `Duration { Invalid, reason: ${this.invalidReason} }`;\n }\n }\n\n /**\n * Returns an milliseconds value of this Duration.\n * @return {number}\n */\n toMillis() {\n if (!this.isValid) return NaN;\n\n return durationToMillis(this.matrix, this.values);\n }\n\n /**\n * Returns an milliseconds value of this Duration. Alias of {@link toMillis}\n * @return {number}\n */\n valueOf() {\n return this.toMillis();\n }\n\n /**\n * Make this Duration longer by the specified amount. Return a newly-constructed Duration.\n * @param {Duration|Object|number} duration - The amount to add. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()\n * @return {Duration}\n */\n plus(duration) {\n if (!this.isValid) return this;\n\n const dur = Duration.fromDurationLike(duration),\n result = {};\n\n for (const k of orderedUnits) {\n if (hasOwnProperty(dur.values, k) || hasOwnProperty(this.values, k)) {\n result[k] = dur.get(k) + this.get(k);\n }\n }\n\n return clone(this, { values: result }, true);\n }\n\n /**\n * Make this Duration shorter by the specified amount. Return a newly-constructed Duration.\n * @param {Duration|Object|number} duration - The amount to subtract. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()\n * @return {Duration}\n */\n minus(duration) {\n if (!this.isValid) return this;\n\n const dur = Duration.fromDurationLike(duration);\n return this.plus(dur.negate());\n }\n\n /**\n * Scale this Duration by the specified amount. Return a newly-constructed Duration.\n * @param {function} fn - The function to apply to each unit. Arity is 1 or 2: the value of the unit and, optionally, the unit name. Must return a number.\n * @example Duration.fromObject({ hours: 1, minutes: 30 }).mapUnits(x => x * 2) //=> { hours: 2, minutes: 60 }\n * @example Duration.fromObject({ hours: 1, minutes: 30 }).mapUnits((x, u) => u === \"hours\" ? x * 2 : x) //=> { hours: 2, minutes: 30 }\n * @return {Duration}\n */\n mapUnits(fn) {\n if (!this.isValid) return this;\n const result = {};\n for (const k of Object.keys(this.values)) {\n result[k] = asNumber(fn(this.values[k], k));\n }\n return clone(this, { values: result }, true);\n }\n\n /**\n * Get the value of unit.\n * @param {string} unit - a unit such as 'minute' or 'day'\n * @example Duration.fromObject({years: 2, days: 3}).get('years') //=> 2\n * @example Duration.fromObject({years: 2, days: 3}).get('months') //=> 0\n * @example Duration.fromObject({years: 2, days: 3}).get('days') //=> 3\n * @return {number}\n */\n get(unit) {\n return this[Duration.normalizeUnit(unit)];\n }\n\n /**\n * \"Set\" the values of specified units. Return a newly-constructed Duration.\n * @param {Object} values - a mapping of units to numbers\n * @example dur.set({ years: 2017 })\n * @example dur.set({ hours: 8, minutes: 30 })\n * @return {Duration}\n */\n set(values) {\n if (!this.isValid) return this;\n\n const mixed = { ...this.values, ...normalizeObject(values, Duration.normalizeUnit) };\n return clone(this, { values: mixed });\n }\n\n /**\n * \"Set\" the locale and/or numberingSystem. Returns a newly-constructed Duration.\n * @example dur.reconfigure({ locale: 'en-GB' })\n * @return {Duration}\n */\n reconfigure({ locale, numberingSystem, conversionAccuracy, matrix } = {}) {\n const loc = this.loc.clone({ locale, numberingSystem });\n const opts = { loc, matrix, conversionAccuracy };\n return clone(this, opts);\n }\n\n /**\n * Return the length of the duration in the specified unit.\n * @param {string} unit - a unit such as 'minutes' or 'days'\n * @example Duration.fromObject({years: 1}).as('days') //=> 365\n * @example Duration.fromObject({years: 1}).as('months') //=> 12\n * @example Duration.fromObject({hours: 60}).as('days') //=> 2.5\n * @return {number}\n */\n as(unit) {\n return this.isValid ? this.shiftTo(unit).get(unit) : NaN;\n }\n\n /**\n * Reduce this Duration to its canonical representation in its current units.\n * Assuming the overall value of the Duration is positive, this means:\n * - excessive values for lower-order units are converted to higher-order units (if possible, see first and second example)\n * - negative lower-order units are converted to higher order units (there must be such a higher order unit, otherwise\n * the overall value would be negative, see third example)\n * - fractional values for higher-order units are converted to lower-order units (if possible, see fourth example)\n *\n * If the overall value is negative, the result of this method is equivalent to `this.negate().normalize().negate()`.\n * @example Duration.fromObject({ years: 2, days: 5000 }).normalize().toObject() //=> { years: 15, days: 255 }\n * @example Duration.fromObject({ days: 5000 }).normalize().toObject() //=> { days: 5000 }\n * @example Duration.fromObject({ hours: 12, minutes: -45 }).normalize().toObject() //=> { hours: 11, minutes: 15 }\n * @example Duration.fromObject({ years: 2.5, days: 0, hours: 0 }).normalize().toObject() //=> { years: 2, days: 182, hours: 12 }\n * @return {Duration}\n */\n normalize() {\n if (!this.isValid) return this;\n const vals = this.toObject();\n normalizeValues(this.matrix, vals);\n return clone(this, { values: vals }, true);\n }\n\n /**\n * Rescale units to its largest representation\n * @example Duration.fromObject({ milliseconds: 90000 }).rescale().toObject() //=> { minutes: 1, seconds: 30 }\n * @return {Duration}\n */\n rescale() {\n if (!this.isValid) return this;\n const vals = removeZeroes(this.normalize().shiftToAll().toObject());\n return clone(this, { values: vals }, true);\n }\n\n /**\n * Convert this Duration into its representation in a different set of units.\n * @example Duration.fromObject({ hours: 1, seconds: 30 }).shiftTo('minutes', 'milliseconds').toObject() //=> { minutes: 60, milliseconds: 30000 }\n * @return {Duration}\n */\n shiftTo(...units) {\n if (!this.isValid) return this;\n\n if (units.length === 0) {\n return this;\n }\n\n units = units.map((u) => Duration.normalizeUnit(u));\n\n const built = {},\n accumulated = {},\n vals = this.toObject();\n let lastUnit;\n\n for (const k of orderedUnits) {\n if (units.indexOf(k) >= 0) {\n lastUnit = k;\n\n let own = 0;\n\n // anything we haven't boiled down yet should get boiled to this unit\n for (const ak in accumulated) {\n own += this.matrix[ak][k] * accumulated[ak];\n accumulated[ak] = 0;\n }\n\n // plus anything that's already in this unit\n if (isNumber(vals[k])) {\n own += vals[k];\n }\n\n // only keep the integer part for now in the hopes of putting any decimal part\n // into a smaller unit later\n const i = Math.trunc(own);\n built[k] = i;\n accumulated[k] = (own * 1000 - i * 1000) / 1000;\n\n // otherwise, keep it in the wings to boil it later\n } else if (isNumber(vals[k])) {\n accumulated[k] = vals[k];\n }\n }\n\n // anything leftover becomes the decimal for the last unit\n // lastUnit must be defined since units is not empty\n for (const key in accumulated) {\n if (accumulated[key] !== 0) {\n built[lastUnit] +=\n key === lastUnit ? accumulated[key] : accumulated[key] / this.matrix[lastUnit][key];\n }\n }\n\n normalizeValues(this.matrix, built);\n return clone(this, { values: built }, true);\n }\n\n /**\n * Shift this Duration to all available units.\n * Same as shiftTo(\"years\", \"months\", \"weeks\", \"days\", \"hours\", \"minutes\", \"seconds\", \"milliseconds\")\n * @return {Duration}\n */\n shiftToAll() {\n if (!this.isValid) return this;\n return this.shiftTo(\n \"years\",\n \"months\",\n \"weeks\",\n \"days\",\n \"hours\",\n \"minutes\",\n \"seconds\",\n \"milliseconds\"\n );\n }\n\n /**\n * Return the negative of this Duration.\n * @example Duration.fromObject({ hours: 1, seconds: 30 }).negate().toObject() //=> { hours: -1, seconds: -30 }\n * @return {Duration}\n */\n negate() {\n if (!this.isValid) return this;\n const negated = {};\n for (const k of Object.keys(this.values)) {\n negated[k] = this.values[k] === 0 ? 0 : -this.values[k];\n }\n return clone(this, { values: negated }, true);\n }\n\n /**\n * Get the years.\n * @type {number}\n */\n get years() {\n return this.isValid ? this.values.years || 0 : NaN;\n }\n\n /**\n * Get the quarters.\n * @type {number}\n */\n get quarters() {\n return this.isValid ? this.values.quarters || 0 : NaN;\n }\n\n /**\n * Get the months.\n * @type {number}\n */\n get months() {\n return this.isValid ? this.values.months || 0 : NaN;\n }\n\n /**\n * Get the weeks\n * @type {number}\n */\n get weeks() {\n return this.isValid ? this.values.weeks || 0 : NaN;\n }\n\n /**\n * Get the days.\n * @type {number}\n */\n get days() {\n return this.isValid ? this.values.days || 0 : NaN;\n }\n\n /**\n * Get the hours.\n * @type {number}\n */\n get hours() {\n return this.isValid ? this.values.hours || 0 : NaN;\n }\n\n /**\n * Get the minutes.\n * @type {number}\n */\n get minutes() {\n return this.isValid ? this.values.minutes || 0 : NaN;\n }\n\n /**\n * Get the seconds.\n * @return {number}\n */\n get seconds() {\n return this.isValid ? this.values.seconds || 0 : NaN;\n }\n\n /**\n * Get the milliseconds.\n * @return {number}\n */\n get milliseconds() {\n return this.isValid ? this.values.milliseconds || 0 : NaN;\n }\n\n /**\n * Returns whether the Duration is invalid. Invalid durations are returned by diff operations\n * on invalid DateTimes or Intervals.\n * @return {boolean}\n */\n get isValid() {\n return this.invalid === null;\n }\n\n /**\n * Returns an error code if this Duration became invalid, or null if the Duration is valid\n * @return {string}\n */\n get invalidReason() {\n return this.invalid ? this.invalid.reason : null;\n }\n\n /**\n * Returns an explanation of why this Duration became invalid, or null if the Duration is valid\n * @type {string}\n */\n get invalidExplanation() {\n return this.invalid ? this.invalid.explanation : null;\n }\n\n /**\n * Equality check\n * Two Durations are equal iff they have the same units and the same values for each unit.\n * @param {Duration} other\n * @return {boolean}\n */\n equals(other) {\n if (!this.isValid || !other.isValid) {\n return false;\n }\n\n if (!this.loc.equals(other.loc)) {\n return false;\n }\n\n function eq(v1, v2) {\n // Consider 0 and undefined as equal\n if (v1 === undefined || v1 === 0) return v2 === undefined || v2 === 0;\n return v1 === v2;\n }\n\n for (const u of orderedUnits) {\n if (!eq(this.values[u], other.values[u])) {\n return false;\n }\n }\n return true;\n }\n}\n", "import DateTime, { friendlyDateTime } from \"./datetime.js\";\nimport Duration from \"./duration.js\";\nimport Settings from \"./settings.js\";\nimport { InvalidArgumentError, InvalidIntervalError } from \"./errors.js\";\nimport Invalid from \"./impl/invalid.js\";\nimport Formatter from \"./impl/formatter.js\";\nimport * as Formats from \"./impl/formats.js\";\n\nconst INVALID = \"Invalid Interval\";\n\n// checks if the start is equal to or before the end\nfunction validateStartEnd(start, end) {\n if (!start || !start.isValid) {\n return Interval.invalid(\"missing or invalid start\");\n } else if (!end || !end.isValid) {\n return Interval.invalid(\"missing or invalid end\");\n } else if (end < start) {\n return Interval.invalid(\n \"end before start\",\n `The end of an interval must be after its start, but you had start=${start.toISO()} and end=${end.toISO()}`\n );\n } else {\n return null;\n }\n}\n\n/**\n * An Interval object represents a half-open interval of time, where each endpoint is a {@link DateTime}. Conceptually, it's a container for those two endpoints, accompanied by methods for creating, parsing, interrogating, comparing, transforming, and formatting them.\n *\n * Here is a brief overview of the most commonly used methods and getters in Interval:\n *\n * * **Creation** To create an Interval, use {@link Interval.fromDateTimes}, {@link Interval.after}, {@link Interval.before}, or {@link Interval.fromISO}.\n * * **Accessors** Use {@link Interval#start} and {@link Interval#end} to get the start and end.\n * * **Interrogation** To analyze the Interval, use {@link Interval#count}, {@link Interval#length}, {@link Interval#hasSame}, {@link Interval#contains}, {@link Interval#isAfter}, or {@link Interval#isBefore}.\n * * **Transformation** To create other Intervals out of this one, use {@link Interval#set}, {@link Interval#splitAt}, {@link Interval#splitBy}, {@link Interval#divideEqually}, {@link Interval.merge}, {@link Interval.xor}, {@link Interval#union}, {@link Interval#intersection}, or {@link Interval#difference}.\n * * **Comparison** To compare this Interval to another one, use {@link Interval#equals}, {@link Interval#overlaps}, {@link Interval#abutsStart}, {@link Interval#abutsEnd}, {@link Interval#engulfs}\n * * **Output** To convert the Interval into other representations, see {@link Interval#toString}, {@link Interval#toLocaleString}, {@link Interval#toISO}, {@link Interval#toISODate}, {@link Interval#toISOTime}, {@link Interval#toFormat}, and {@link Interval#toDuration}.\n */\nexport default class Interval {\n /**\n * @private\n */\n constructor(config) {\n /**\n * @access private\n */\n this.s = config.start;\n /**\n * @access private\n */\n this.e = config.end;\n /**\n * @access private\n */\n this.invalid = config.invalid || null;\n /**\n * @access private\n */\n this.isLuxonInterval = true;\n }\n\n /**\n * Create an invalid Interval.\n * @param {string} reason - simple string of why this Interval is invalid. Should not contain parameters or anything else data-dependent\n * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information\n * @return {Interval}\n */\n static invalid(reason, explanation = null) {\n if (!reason) {\n throw new InvalidArgumentError(\"need to specify a reason the Interval is invalid\");\n }\n\n const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation);\n\n if (Settings.throwOnInvalid) {\n throw new InvalidIntervalError(invalid);\n } else {\n return new Interval({ invalid });\n }\n }\n\n /**\n * Create an Interval from a start DateTime and an end DateTime. Inclusive of the start but not the end.\n * @param {DateTime|Date|Object} start\n * @param {DateTime|Date|Object} end\n * @return {Interval}\n */\n static fromDateTimes(start, end) {\n const builtStart = friendlyDateTime(start),\n builtEnd = friendlyDateTime(end);\n\n const validateError = validateStartEnd(builtStart, builtEnd);\n\n if (validateError == null) {\n return new Interval({\n start: builtStart,\n end: builtEnd,\n });\n } else {\n return validateError;\n }\n }\n\n /**\n * Create an Interval from a start DateTime and a Duration to extend to.\n * @param {DateTime|Date|Object} start\n * @param {Duration|Object|number} duration - the length of the Interval.\n * @return {Interval}\n */\n static after(start, duration) {\n const dur = Duration.fromDurationLike(duration),\n dt = friendlyDateTime(start);\n return Interval.fromDateTimes(dt, dt.plus(dur));\n }\n\n /**\n * Create an Interval from an end DateTime and a Duration to extend backwards to.\n * @param {DateTime|Date|Object} end\n * @param {Duration|Object|number} duration - the length of the Interval.\n * @return {Interval}\n */\n static before(end, duration) {\n const dur = Duration.fromDurationLike(duration),\n dt = friendlyDateTime(end);\n return Interval.fromDateTimes(dt.minus(dur), dt);\n }\n\n /**\n * Create an Interval from an ISO 8601 string.\n * Accepts `/`, `/`, and `/` formats.\n * @param {string} text - the ISO string to parse\n * @param {Object} [opts] - options to pass {@link DateTime#fromISO} and optionally {@link Duration#fromISO}\n * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals\n * @return {Interval}\n */\n static fromISO(text, opts) {\n const [s, e] = (text || \"\").split(\"/\", 2);\n if (s && e) {\n let start, startIsValid;\n try {\n start = DateTime.fromISO(s, opts);\n startIsValid = start.isValid;\n } catch (e) {\n startIsValid = false;\n }\n\n let end, endIsValid;\n try {\n end = DateTime.fromISO(e, opts);\n endIsValid = end.isValid;\n } catch (e) {\n endIsValid = false;\n }\n\n if (startIsValid && endIsValid) {\n return Interval.fromDateTimes(start, end);\n }\n\n if (startIsValid) {\n const dur = Duration.fromISO(e, opts);\n if (dur.isValid) {\n return Interval.after(start, dur);\n }\n } else if (endIsValid) {\n const dur = Duration.fromISO(s, opts);\n if (dur.isValid) {\n return Interval.before(end, dur);\n }\n }\n }\n return Interval.invalid(\"unparsable\", `the input \"${text}\" can't be parsed as ISO 8601`);\n }\n\n /**\n * Check if an object is an Interval. Works across context boundaries\n * @param {object} o\n * @return {boolean}\n */\n static isInterval(o) {\n return (o && o.isLuxonInterval) || false;\n }\n\n /**\n * Returns the start of the Interval\n * @type {DateTime}\n */\n get start() {\n return this.isValid ? this.s : null;\n }\n\n /**\n * Returns the end of the Interval\n * @type {DateTime}\n */\n get end() {\n return this.isValid ? this.e : null;\n }\n\n /**\n * Returns whether this Interval's end is at least its start, meaning that the Interval isn't 'backwards'.\n * @type {boolean}\n */\n get isValid() {\n return this.invalidReason === null;\n }\n\n /**\n * Returns an error code if this Interval is invalid, or null if the Interval is valid\n * @type {string}\n */\n get invalidReason() {\n return this.invalid ? this.invalid.reason : null;\n }\n\n /**\n * Returns an explanation of why this Interval became invalid, or null if the Interval is valid\n * @type {string}\n */\n get invalidExplanation() {\n return this.invalid ? this.invalid.explanation : null;\n }\n\n /**\n * Returns the length of the Interval in the specified unit.\n * @param {string} unit - the unit (such as 'hours' or 'days') to return the length in.\n * @return {number}\n */\n length(unit = \"milliseconds\") {\n return this.isValid ? this.toDuration(...[unit]).get(unit) : NaN;\n }\n\n /**\n * Returns the count of minutes, hours, days, months, or years included in the Interval, even in part.\n * Unlike {@link Interval#length} this counts sections of the calendar, not periods of time, e.g. specifying 'day'\n * asks 'what dates are included in this interval?', not 'how many days long is this interval?'\n * @param {string} [unit='milliseconds'] - the unit of time to count.\n * @param {Object} opts - options\n * @param {boolean} [opts.useLocaleWeeks=false] - If true, use weeks based on the locale, i.e. use the locale-dependent start of the week; this operation will always use the locale of the start DateTime\n * @return {number}\n */\n count(unit = \"milliseconds\", opts) {\n if (!this.isValid) return NaN;\n const start = this.start.startOf(unit, opts);\n let end;\n if (opts?.useLocaleWeeks) {\n end = this.end.reconfigure({ locale: start.locale });\n } else {\n end = this.end;\n }\n end = end.startOf(unit, opts);\n return Math.floor(end.diff(start, unit).get(unit)) + (end.valueOf() !== this.end.valueOf());\n }\n\n /**\n * Returns whether this Interval's start and end are both in the same unit of time\n * @param {string} unit - the unit of time to check sameness on\n * @return {boolean}\n */\n hasSame(unit) {\n return this.isValid ? this.isEmpty() || this.e.minus(1).hasSame(this.s, unit) : false;\n }\n\n /**\n * Return whether this Interval has the same start and end DateTimes.\n * @return {boolean}\n */\n isEmpty() {\n return this.s.valueOf() === this.e.valueOf();\n }\n\n /**\n * Return whether this Interval's start is after the specified DateTime.\n * @param {DateTime} dateTime\n * @return {boolean}\n */\n isAfter(dateTime) {\n if (!this.isValid) return false;\n return this.s > dateTime;\n }\n\n /**\n * Return whether this Interval's end is before the specified DateTime.\n * @param {DateTime} dateTime\n * @return {boolean}\n */\n isBefore(dateTime) {\n if (!this.isValid) return false;\n return this.e <= dateTime;\n }\n\n /**\n * Return whether this Interval contains the specified DateTime.\n * @param {DateTime} dateTime\n * @return {boolean}\n */\n contains(dateTime) {\n if (!this.isValid) return false;\n return this.s <= dateTime && this.e > dateTime;\n }\n\n /**\n * \"Sets\" the start and/or end dates. Returns a newly-constructed Interval.\n * @param {Object} values - the values to set\n * @param {DateTime} values.start - the starting DateTime\n * @param {DateTime} values.end - the ending DateTime\n * @return {Interval}\n */\n set({ start, end } = {}) {\n if (!this.isValid) return this;\n return Interval.fromDateTimes(start || this.s, end || this.e);\n }\n\n /**\n * Split this Interval at each of the specified DateTimes\n * @param {...DateTime} dateTimes - the unit of time to count.\n * @return {Array}\n */\n splitAt(...dateTimes) {\n if (!this.isValid) return [];\n const sorted = dateTimes\n .map(friendlyDateTime)\n .filter((d) => this.contains(d))\n .sort((a, b) => a.toMillis() - b.toMillis()),\n results = [];\n let { s } = this,\n i = 0;\n\n while (s < this.e) {\n const added = sorted[i] || this.e,\n next = +added > +this.e ? this.e : added;\n results.push(Interval.fromDateTimes(s, next));\n s = next;\n i += 1;\n }\n\n return results;\n }\n\n /**\n * Split this Interval into smaller Intervals, each of the specified length.\n * Left over time is grouped into a smaller interval\n * @param {Duration|Object|number} duration - The length of each resulting interval.\n * @return {Array}\n */\n splitBy(duration) {\n const dur = Duration.fromDurationLike(duration);\n\n if (!this.isValid || !dur.isValid || dur.as(\"milliseconds\") === 0) {\n return [];\n }\n\n let { s } = this,\n idx = 1,\n next;\n\n const results = [];\n while (s < this.e) {\n const added = this.start.plus(dur.mapUnits((x) => x * idx));\n next = +added > +this.e ? this.e : added;\n results.push(Interval.fromDateTimes(s, next));\n s = next;\n idx += 1;\n }\n\n return results;\n }\n\n /**\n * Split this Interval into the specified number of smaller intervals.\n * @param {number} numberOfParts - The number of Intervals to divide the Interval into.\n * @return {Array}\n */\n divideEqually(numberOfParts) {\n if (!this.isValid) return [];\n return this.splitBy(this.length() / numberOfParts).slice(0, numberOfParts);\n }\n\n /**\n * Return whether this Interval overlaps with the specified Interval\n * @param {Interval} other\n * @return {boolean}\n */\n overlaps(other) {\n return this.e > other.s && this.s < other.e;\n }\n\n /**\n * Return whether this Interval's end is adjacent to the specified Interval's start.\n * @param {Interval} other\n * @return {boolean}\n */\n abutsStart(other) {\n if (!this.isValid) return false;\n return +this.e === +other.s;\n }\n\n /**\n * Return whether this Interval's start is adjacent to the specified Interval's end.\n * @param {Interval} other\n * @return {boolean}\n */\n abutsEnd(other) {\n if (!this.isValid) return false;\n return +other.e === +this.s;\n }\n\n /**\n * Returns true if this Interval fully contains the specified Interval, specifically if the intersect (of this Interval and the other Interval) is equal to the other Interval; false otherwise.\n * @param {Interval} other\n * @return {boolean}\n */\n engulfs(other) {\n if (!this.isValid) return false;\n return this.s <= other.s && this.e >= other.e;\n }\n\n /**\n * Return whether this Interval has the same start and end as the specified Interval.\n * @param {Interval} other\n * @return {boolean}\n */\n equals(other) {\n if (!this.isValid || !other.isValid) {\n return false;\n }\n\n return this.s.equals(other.s) && this.e.equals(other.e);\n }\n\n /**\n * Return an Interval representing the intersection of this Interval and the specified Interval.\n * Specifically, the resulting Interval has the maximum start time and the minimum end time of the two Intervals.\n * Returns null if the intersection is empty, meaning, the intervals don't intersect.\n * @param {Interval} other\n * @return {Interval}\n */\n intersection(other) {\n if (!this.isValid) return this;\n const s = this.s > other.s ? this.s : other.s,\n e = this.e < other.e ? this.e : other.e;\n\n if (s >= e) {\n return null;\n } else {\n return Interval.fromDateTimes(s, e);\n }\n }\n\n /**\n * Return an Interval representing the union of this Interval and the specified Interval.\n * Specifically, the resulting Interval has the minimum start time and the maximum end time of the two Intervals.\n * @param {Interval} other\n * @return {Interval}\n */\n union(other) {\n if (!this.isValid) return this;\n const s = this.s < other.s ? this.s : other.s,\n e = this.e > other.e ? this.e : other.e;\n return Interval.fromDateTimes(s, e);\n }\n\n /**\n * Merge an array of Intervals into a equivalent minimal set of Intervals.\n * Combines overlapping and adjacent Intervals.\n * @param {Array} intervals\n * @return {Array}\n */\n static merge(intervals) {\n const [found, final] = intervals\n .sort((a, b) => a.s - b.s)\n .reduce(\n ([sofar, current], item) => {\n if (!current) {\n return [sofar, item];\n } else if (current.overlaps(item) || current.abutsStart(item)) {\n return [sofar, current.union(item)];\n } else {\n return [sofar.concat([current]), item];\n }\n },\n [[], null]\n );\n if (final) {\n found.push(final);\n }\n return found;\n }\n\n /**\n * Return an array of Intervals representing the spans of time that only appear in one of the specified Intervals.\n * @param {Array} intervals\n * @return {Array}\n */\n static xor(intervals) {\n let start = null,\n currentCount = 0;\n const results = [],\n ends = intervals.map((i) => [\n { time: i.s, type: \"s\" },\n { time: i.e, type: \"e\" },\n ]),\n flattened = Array.prototype.concat(...ends),\n arr = flattened.sort((a, b) => a.time - b.time);\n\n for (const i of arr) {\n currentCount += i.type === \"s\" ? 1 : -1;\n\n if (currentCount === 1) {\n start = i.time;\n } else {\n if (start && +start !== +i.time) {\n results.push(Interval.fromDateTimes(start, i.time));\n }\n\n start = null;\n }\n }\n\n return Interval.merge(results);\n }\n\n /**\n * Return an Interval representing the span of time in this Interval that doesn't overlap with any of the specified Intervals.\n * @param {...Interval} intervals\n * @return {Array}\n */\n difference(...intervals) {\n return Interval.xor([this].concat(intervals))\n .map((i) => this.intersection(i))\n .filter((i) => i && !i.isEmpty());\n }\n\n /**\n * Returns a string representation of this Interval appropriate for debugging.\n * @return {string}\n */\n toString() {\n if (!this.isValid) return INVALID;\n return `[${this.s.toISO()} \u2013 ${this.e.toISO()})`;\n }\n\n /**\n * Returns a string representation of this Interval appropriate for the REPL.\n * @return {string}\n */\n [Symbol.for(\"nodejs.util.inspect.custom\")]() {\n if (this.isValid) {\n return `Interval { start: ${this.s.toISO()}, end: ${this.e.toISO()} }`;\n } else {\n return `Interval { Invalid, reason: ${this.invalidReason} }`;\n }\n }\n\n /**\n * Returns a localized string representing this Interval. Accepts the same options as the\n * Intl.DateTimeFormat constructor and any presets defined by Luxon, such as\n * {@link DateTime.DATE_FULL} or {@link DateTime.TIME_SIMPLE}. The exact behavior of this method\n * is browser-specific, but in general it will return an appropriate representation of the\n * Interval in the assigned locale. Defaults to the system's locale if no locale has been\n * specified.\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat\n * @param {Object} [formatOpts=DateTime.DATE_SHORT] - Either a DateTime preset or\n * Intl.DateTimeFormat constructor options.\n * @param {Object} opts - Options to override the configuration of the start DateTime.\n * @example Interval.fromISO('2022-11-07T09:00Z/2022-11-08T09:00Z').toLocaleString(); //=> 11/7/2022 \u2013 11/8/2022\n * @example Interval.fromISO('2022-11-07T09:00Z/2022-11-08T09:00Z').toLocaleString(DateTime.DATE_FULL); //=> November 7 \u2013 8, 2022\n * @example Interval.fromISO('2022-11-07T09:00Z/2022-11-08T09:00Z').toLocaleString(DateTime.DATE_FULL, { locale: 'fr-FR' }); //=> 7\u20138 novembre 2022\n * @example Interval.fromISO('2022-11-07T17:00Z/2022-11-07T19:00Z').toLocaleString(DateTime.TIME_SIMPLE); //=> 6:00 \u2013 8:00 PM\n * @example Interval.fromISO('2022-11-07T17:00Z/2022-11-07T19:00Z').toLocaleString({ weekday: 'short', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit' }); //=> Mon, Nov 07, 6:00 \u2013 8:00 p\n * @return {string}\n */\n toLocaleString(formatOpts = Formats.DATE_SHORT, opts = {}) {\n return this.isValid\n ? Formatter.create(this.s.loc.clone(opts), formatOpts).formatInterval(this)\n : INVALID;\n }\n\n /**\n * Returns an ISO 8601-compliant string representation of this Interval.\n * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals\n * @param {Object} opts - The same options as {@link DateTime#toISO}\n * @return {string}\n */\n toISO(opts) {\n if (!this.isValid) return INVALID;\n return `${this.s.toISO(opts)}/${this.e.toISO(opts)}`;\n }\n\n /**\n * Returns an ISO 8601-compliant string representation of date of this Interval.\n * The time components are ignored.\n * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals\n * @return {string}\n */\n toISODate() {\n if (!this.isValid) return INVALID;\n return `${this.s.toISODate()}/${this.e.toISODate()}`;\n }\n\n /**\n * Returns an ISO 8601-compliant string representation of time of this Interval.\n * The date components are ignored.\n * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals\n * @param {Object} opts - The same options as {@link DateTime#toISO}\n * @return {string}\n */\n toISOTime(opts) {\n if (!this.isValid) return INVALID;\n return `${this.s.toISOTime(opts)}/${this.e.toISOTime(opts)}`;\n }\n\n /**\n * Returns a string representation of this Interval formatted according to the specified format\n * string. **You may not want this.** See {@link Interval#toLocaleString} for a more flexible\n * formatting tool.\n * @param {string} dateFormat - The format string. This string formats the start and end time.\n * See {@link DateTime#toFormat} for details.\n * @param {Object} opts - Options.\n * @param {string} [opts.separator = ' \u2013 '] - A separator to place between the start and end\n * representations.\n * @return {string}\n */\n toFormat(dateFormat, { separator = \" \u2013 \" } = {}) {\n if (!this.isValid) return INVALID;\n return `${this.s.toFormat(dateFormat)}${separator}${this.e.toFormat(dateFormat)}`;\n }\n\n /**\n * Return a Duration representing the time spanned by this interval.\n * @param {string|string[]} [unit=['milliseconds']] - the unit or units (such as 'hours' or 'days') to include in the duration.\n * @param {Object} opts - options that affect the creation of the Duration\n * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use\n * @example Interval.fromDateTimes(dt1, dt2).toDuration().toObject() //=> { milliseconds: 88489257 }\n * @example Interval.fromDateTimes(dt1, dt2).toDuration('days').toObject() //=> { days: 1.0241812152777778 }\n * @example Interval.fromDateTimes(dt1, dt2).toDuration(['hours', 'minutes']).toObject() //=> { hours: 24, minutes: 34.82095 }\n * @example Interval.fromDateTimes(dt1, dt2).toDuration(['hours', 'minutes', 'seconds']).toObject() //=> { hours: 24, minutes: 34, seconds: 49.257 }\n * @example Interval.fromDateTimes(dt1, dt2).toDuration('seconds').toObject() //=> { seconds: 88489.257 }\n * @return {Duration}\n */\n toDuration(unit, opts) {\n if (!this.isValid) {\n return Duration.invalid(this.invalidReason);\n }\n return this.e.diff(this.s, unit, opts);\n }\n\n /**\n * Run mapFn on the interval start and end, returning a new Interval from the resulting DateTimes\n * @param {function} mapFn\n * @return {Interval}\n * @example Interval.fromDateTimes(dt1, dt2).mapEndpoints(endpoint => endpoint.toUTC())\n * @example Interval.fromDateTimes(dt1, dt2).mapEndpoints(endpoint => endpoint.plus({ hours: 2 }))\n */\n mapEndpoints(mapFn) {\n return Interval.fromDateTimes(mapFn(this.s), mapFn(this.e));\n }\n}\n", "import DateTime from \"./datetime.js\";\nimport Settings from \"./settings.js\";\nimport Locale from \"./impl/locale.js\";\nimport IANAZone from \"./zones/IANAZone.js\";\nimport { normalizeZone } from \"./impl/zoneUtil.js\";\n\nimport { hasLocaleWeekInfo, hasRelative } from \"./impl/util.js\";\n\n/**\n * The Info class contains static methods for retrieving general time and date related data. For example, it has methods for finding out if a time zone has a DST, for listing the months in any supported locale, and for discovering which of Luxon features are available in the current environment.\n */\nexport default class Info {\n /**\n * Return whether the specified zone contains a DST.\n * @param {string|Zone} [zone='local'] - Zone to check. Defaults to the environment's local zone.\n * @return {boolean}\n */\n static hasDST(zone = Settings.defaultZone) {\n const proto = DateTime.now().setZone(zone).set({ month: 12 });\n\n return !zone.isUniversal && proto.offset !== proto.set({ month: 6 }).offset;\n }\n\n /**\n * Return whether the specified zone is a valid IANA specifier.\n * @param {string} zone - Zone to check\n * @return {boolean}\n */\n static isValidIANAZone(zone) {\n return IANAZone.isValidZone(zone);\n }\n\n /**\n * Converts the input into a {@link Zone} instance.\n *\n * * If `input` is already a Zone instance, it is returned unchanged.\n * * If `input` is a string containing a valid time zone name, a Zone instance\n * with that name is returned.\n * * If `input` is a string that doesn't refer to a known time zone, a Zone\n * instance with {@link Zone#isValid} == false is returned.\n * * If `input is a number, a Zone instance with the specified fixed offset\n * in minutes is returned.\n * * If `input` is `null` or `undefined`, the default zone is returned.\n * @param {string|Zone|number} [input] - the value to be converted\n * @return {Zone}\n */\n static normalizeZone(input) {\n return normalizeZone(input, Settings.defaultZone);\n }\n\n /**\n * Get the weekday on which the week starts according to the given locale.\n * @param {Object} opts - options\n * @param {string} [opts.locale] - the locale code\n * @param {string} [opts.locObj=null] - an existing locale object to use\n * @returns {number} the start of the week, 1 for Monday through 7 for Sunday\n */\n static getStartOfWeek({ locale = null, locObj = null } = {}) {\n return (locObj || Locale.create(locale)).getStartOfWeek();\n }\n\n /**\n * Get the minimum number of days necessary in a week before it is considered part of the next year according\n * to the given locale.\n * @param {Object} opts - options\n * @param {string} [opts.locale] - the locale code\n * @param {string} [opts.locObj=null] - an existing locale object to use\n * @returns {number}\n */\n static getMinimumDaysInFirstWeek({ locale = null, locObj = null } = {}) {\n return (locObj || Locale.create(locale)).getMinDaysInFirstWeek();\n }\n\n /**\n * Get the weekdays, which are considered the weekend according to the given locale\n * @param {Object} opts - options\n * @param {string} [opts.locale] - the locale code\n * @param {string} [opts.locObj=null] - an existing locale object to use\n * @returns {number[]} an array of weekdays, 1 for Monday through 7 for Sunday\n */\n static getWeekendWeekdays({ locale = null, locObj = null } = {}) {\n // copy the array, because we cache it internally\n return (locObj || Locale.create(locale)).getWeekendDays().slice();\n }\n\n /**\n * Return an array of standalone month names.\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat\n * @param {string} [length='long'] - the length of the month representation, such as \"numeric\", \"2-digit\", \"narrow\", \"short\", \"long\"\n * @param {Object} opts - options\n * @param {string} [opts.locale] - the locale code\n * @param {string} [opts.numberingSystem=null] - the numbering system\n * @param {string} [opts.locObj=null] - an existing locale object to use\n * @param {string} [opts.outputCalendar='gregory'] - the calendar\n * @example Info.months()[0] //=> 'January'\n * @example Info.months('short')[0] //=> 'Jan'\n * @example Info.months('numeric')[0] //=> '1'\n * @example Info.months('short', { locale: 'fr-CA' } )[0] //=> 'janv.'\n * @example Info.months('numeric', { locale: 'ar' })[0] //=> '\u0661'\n * @example Info.months('long', { outputCalendar: 'islamic' })[0] //=> 'Rabi\u02BB I'\n * @return {Array}\n */\n static months(\n length = \"long\",\n { locale = null, numberingSystem = null, locObj = null, outputCalendar = \"gregory\" } = {}\n ) {\n return (locObj || Locale.create(locale, numberingSystem, outputCalendar)).months(length);\n }\n\n /**\n * Return an array of format month names.\n * Format months differ from standalone months in that they're meant to appear next to the day of the month. In some languages, that\n * changes the string.\n * See {@link Info#months}\n * @param {string} [length='long'] - the length of the month representation, such as \"numeric\", \"2-digit\", \"narrow\", \"short\", \"long\"\n * @param {Object} opts - options\n * @param {string} [opts.locale] - the locale code\n * @param {string} [opts.numberingSystem=null] - the numbering system\n * @param {string} [opts.locObj=null] - an existing locale object to use\n * @param {string} [opts.outputCalendar='gregory'] - the calendar\n * @return {Array}\n */\n static monthsFormat(\n length = \"long\",\n { locale = null, numberingSystem = null, locObj = null, outputCalendar = \"gregory\" } = {}\n ) {\n return (locObj || Locale.create(locale, numberingSystem, outputCalendar)).months(length, true);\n }\n\n /**\n * Return an array of standalone week names.\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat\n * @param {string} [length='long'] - the length of the weekday representation, such as \"narrow\", \"short\", \"long\".\n * @param {Object} opts - options\n * @param {string} [opts.locale] - the locale code\n * @param {string} [opts.numberingSystem=null] - the numbering system\n * @param {string} [opts.locObj=null] - an existing locale object to use\n * @example Info.weekdays()[0] //=> 'Monday'\n * @example Info.weekdays('short')[0] //=> 'Mon'\n * @example Info.weekdays('short', { locale: 'fr-CA' })[0] //=> 'lun.'\n * @example Info.weekdays('short', { locale: 'ar' })[0] //=> '\u0627\u0644\u0627\u062B\u0646\u064A\u0646'\n * @return {Array}\n */\n static weekdays(length = \"long\", { locale = null, numberingSystem = null, locObj = null } = {}) {\n return (locObj || Locale.create(locale, numberingSystem, null)).weekdays(length);\n }\n\n /**\n * Return an array of format week names.\n * Format weekdays differ from standalone weekdays in that they're meant to appear next to more date information. In some languages, that\n * changes the string.\n * See {@link Info#weekdays}\n * @param {string} [length='long'] - the length of the month representation, such as \"narrow\", \"short\", \"long\".\n * @param {Object} opts - options\n * @param {string} [opts.locale=null] - the locale code\n * @param {string} [opts.numberingSystem=null] - the numbering system\n * @param {string} [opts.locObj=null] - an existing locale object to use\n * @return {Array}\n */\n static weekdaysFormat(\n length = \"long\",\n { locale = null, numberingSystem = null, locObj = null } = {}\n ) {\n return (locObj || Locale.create(locale, numberingSystem, null)).weekdays(length, true);\n }\n\n /**\n * Return an array of meridiems.\n * @param {Object} opts - options\n * @param {string} [opts.locale] - the locale code\n * @example Info.meridiems() //=> [ 'AM', 'PM' ]\n * @example Info.meridiems({ locale: 'my' }) //=> [ '\u1014\u1036\u1014\u1000\u103A', '\u100A\u1014\u1031' ]\n * @return {Array}\n */\n static meridiems({ locale = null } = {}) {\n return Locale.create(locale).meridiems();\n }\n\n /**\n * Return an array of eras, such as ['BC', 'AD']. The locale can be specified, but the calendar system is always Gregorian.\n * @param {string} [length='short'] - the length of the era representation, such as \"short\" or \"long\".\n * @param {Object} opts - options\n * @param {string} [opts.locale] - the locale code\n * @example Info.eras() //=> [ 'BC', 'AD' ]\n * @example Info.eras('long') //=> [ 'Before Christ', 'Anno Domini' ]\n * @example Info.eras('long', { locale: 'fr' }) //=> [ 'avant J\u00E9sus-Christ', 'apr\u00E8s J\u00E9sus-Christ' ]\n * @return {Array}\n */\n static eras(length = \"short\", { locale = null } = {}) {\n return Locale.create(locale, null, \"gregory\").eras(length);\n }\n\n /**\n * Return the set of available features in this environment.\n * Some features of Luxon are not available in all environments. For example, on older browsers, relative time formatting support is not available. Use this function to figure out if that's the case.\n * Keys:\n * * `relative`: whether this environment supports relative time formatting\n * * `localeWeek`: whether this environment supports different weekdays for the start of the week based on the locale\n * @example Info.features() //=> { relative: false, localeWeek: true }\n * @return {Object}\n */\n static features() {\n return { relative: hasRelative(), localeWeek: hasLocaleWeekInfo() };\n }\n}\n", "import Duration from \"../duration.js\";\n\nfunction dayDiff(earlier, later) {\n const utcDayStart = (dt) => dt.toUTC(0, { keepLocalTime: true }).startOf(\"day\").valueOf(),\n ms = utcDayStart(later) - utcDayStart(earlier);\n return Math.floor(Duration.fromMillis(ms).as(\"days\"));\n}\n\nfunction highOrderDiffs(cursor, later, units) {\n const differs = [\n [\"years\", (a, b) => b.year - a.year],\n [\"quarters\", (a, b) => b.quarter - a.quarter + (b.year - a.year) * 4],\n [\"months\", (a, b) => b.month - a.month + (b.year - a.year) * 12],\n [\n \"weeks\",\n (a, b) => {\n const days = dayDiff(a, b);\n return (days - (days % 7)) / 7;\n },\n ],\n [\"days\", dayDiff],\n ];\n\n const results = {};\n const earlier = cursor;\n let lowestOrder, highWater;\n\n /* This loop tries to diff using larger units first.\n If we overshoot, we backtrack and try the next smaller unit.\n \"cursor\" starts out at the earlier timestamp and moves closer and closer to \"later\"\n as we use smaller and smaller units.\n highWater keeps track of where we would be if we added one more of the smallest unit,\n this is used later to potentially convert any difference smaller than the smallest higher order unit\n into a fraction of that smallest higher order unit\n */\n for (const [unit, differ] of differs) {\n if (units.indexOf(unit) >= 0) {\n lowestOrder = unit;\n\n results[unit] = differ(cursor, later);\n highWater = earlier.plus(results);\n\n if (highWater > later) {\n // we overshot the end point, backtrack cursor by 1\n results[unit]--;\n cursor = earlier.plus(results);\n\n // if we are still overshooting now, we need to backtrack again\n // this happens in certain situations when diffing times in different zones,\n // because this calculation ignores time zones\n if (cursor > later) {\n // keep the \"overshot by 1\" around as highWater\n highWater = cursor;\n // backtrack cursor by 1\n results[unit]--;\n cursor = earlier.plus(results);\n }\n } else {\n cursor = highWater;\n }\n }\n }\n\n return [cursor, results, highWater, lowestOrder];\n}\n\nexport default function (earlier, later, units, opts) {\n let [cursor, results, highWater, lowestOrder] = highOrderDiffs(earlier, later, units);\n\n const remainingMillis = later - cursor;\n\n const lowerOrderUnits = units.filter(\n (u) => [\"hours\", \"minutes\", \"seconds\", \"milliseconds\"].indexOf(u) >= 0\n );\n\n if (lowerOrderUnits.length === 0) {\n if (highWater < later) {\n highWater = cursor.plus({ [lowestOrder]: 1 });\n }\n\n if (highWater !== cursor) {\n results[lowestOrder] = (results[lowestOrder] || 0) + remainingMillis / (highWater - cursor);\n }\n }\n\n const duration = Duration.fromObject(results, opts);\n\n if (lowerOrderUnits.length > 0) {\n return Duration.fromMillis(remainingMillis, opts)\n .shiftTo(...lowerOrderUnits)\n .plus(duration);\n } else {\n return duration;\n }\n}\n", "import { parseMillis, isUndefined, untruncateYear, signedOffset, hasOwnProperty } from \"./util.js\";\nimport Formatter from \"./formatter.js\";\nimport FixedOffsetZone from \"../zones/fixedOffsetZone.js\";\nimport IANAZone from \"../zones/IANAZone.js\";\nimport DateTime from \"../datetime.js\";\nimport { digitRegex, parseDigits } from \"./digits.js\";\nimport { ConflictingSpecificationError } from \"../errors.js\";\n\nconst MISSING_FTP = \"missing Intl.DateTimeFormat.formatToParts support\";\n\nfunction intUnit(regex, post = (i) => i) {\n return { regex, deser: ([s]) => post(parseDigits(s)) };\n}\n\nconst NBSP = String.fromCharCode(160);\nconst spaceOrNBSP = `[ ${NBSP}]`;\nconst spaceOrNBSPRegExp = new RegExp(spaceOrNBSP, \"g\");\n\nfunction fixListRegex(s) {\n // make dots optional and also make them literal\n // make space and non breakable space characters interchangeable\n return s.replace(/\\./g, \"\\\\.?\").replace(spaceOrNBSPRegExp, spaceOrNBSP);\n}\n\nfunction stripInsensitivities(s) {\n return s\n .replace(/\\./g, \"\") // ignore dots that were made optional\n .replace(spaceOrNBSPRegExp, \" \") // interchange space and nbsp\n .toLowerCase();\n}\n\nfunction oneOf(strings, startIndex) {\n if (strings === null) {\n return null;\n } else {\n return {\n regex: RegExp(strings.map(fixListRegex).join(\"|\")),\n deser: ([s]) =>\n strings.findIndex((i) => stripInsensitivities(s) === stripInsensitivities(i)) + startIndex,\n };\n }\n}\n\nfunction offset(regex, groups) {\n return { regex, deser: ([, h, m]) => signedOffset(h, m), groups };\n}\n\nfunction simple(regex) {\n return { regex, deser: ([s]) => s };\n}\n\nfunction escapeToken(value) {\n return value.replace(/[\\-\\[\\]{}()*+?.,\\\\\\^$|#\\s]/g, \"\\\\$&\");\n}\n\n/**\n * @param token\n * @param {Locale} loc\n */\nfunction unitForToken(token, loc) {\n const one = digitRegex(loc),\n two = digitRegex(loc, \"{2}\"),\n three = digitRegex(loc, \"{3}\"),\n four = digitRegex(loc, \"{4}\"),\n six = digitRegex(loc, \"{6}\"),\n oneOrTwo = digitRegex(loc, \"{1,2}\"),\n oneToThree = digitRegex(loc, \"{1,3}\"),\n oneToSix = digitRegex(loc, \"{1,6}\"),\n oneToNine = digitRegex(loc, \"{1,9}\"),\n twoToFour = digitRegex(loc, \"{2,4}\"),\n fourToSix = digitRegex(loc, \"{4,6}\"),\n literal = (t) => ({ regex: RegExp(escapeToken(t.val)), deser: ([s]) => s, literal: true }),\n unitate = (t) => {\n if (token.literal) {\n return literal(t);\n }\n switch (t.val) {\n // era\n case \"G\":\n return oneOf(loc.eras(\"short\"), 0);\n case \"GG\":\n return oneOf(loc.eras(\"long\"), 0);\n // years\n case \"y\":\n return intUnit(oneToSix);\n case \"yy\":\n return intUnit(twoToFour, untruncateYear);\n case \"yyyy\":\n return intUnit(four);\n case \"yyyyy\":\n return intUnit(fourToSix);\n case \"yyyyyy\":\n return intUnit(six);\n // months\n case \"M\":\n return intUnit(oneOrTwo);\n case \"MM\":\n return intUnit(two);\n case \"MMM\":\n return oneOf(loc.months(\"short\", true), 1);\n case \"MMMM\":\n return oneOf(loc.months(\"long\", true), 1);\n case \"L\":\n return intUnit(oneOrTwo);\n case \"LL\":\n return intUnit(two);\n case \"LLL\":\n return oneOf(loc.months(\"short\", false), 1);\n case \"LLLL\":\n return oneOf(loc.months(\"long\", false), 1);\n // dates\n case \"d\":\n return intUnit(oneOrTwo);\n case \"dd\":\n return intUnit(two);\n // ordinals\n case \"o\":\n return intUnit(oneToThree);\n case \"ooo\":\n return intUnit(three);\n // time\n case \"HH\":\n return intUnit(two);\n case \"H\":\n return intUnit(oneOrTwo);\n case \"hh\":\n return intUnit(two);\n case \"h\":\n return intUnit(oneOrTwo);\n case \"mm\":\n return intUnit(two);\n case \"m\":\n return intUnit(oneOrTwo);\n case \"q\":\n return intUnit(oneOrTwo);\n case \"qq\":\n return intUnit(two);\n case \"s\":\n return intUnit(oneOrTwo);\n case \"ss\":\n return intUnit(two);\n case \"S\":\n return intUnit(oneToThree);\n case \"SSS\":\n return intUnit(three);\n case \"u\":\n return simple(oneToNine);\n case \"uu\":\n return simple(oneOrTwo);\n case \"uuu\":\n return intUnit(one);\n // meridiem\n case \"a\":\n return oneOf(loc.meridiems(), 0);\n // weekYear (k)\n case \"kkkk\":\n return intUnit(four);\n case \"kk\":\n return intUnit(twoToFour, untruncateYear);\n // weekNumber (W)\n case \"W\":\n return intUnit(oneOrTwo);\n case \"WW\":\n return intUnit(two);\n // weekdays\n case \"E\":\n case \"c\":\n return intUnit(one);\n case \"EEE\":\n return oneOf(loc.weekdays(\"short\", false), 1);\n case \"EEEE\":\n return oneOf(loc.weekdays(\"long\", false), 1);\n case \"ccc\":\n return oneOf(loc.weekdays(\"short\", true), 1);\n case \"cccc\":\n return oneOf(loc.weekdays(\"long\", true), 1);\n // offset/zone\n case \"Z\":\n case \"ZZ\":\n return offset(new RegExp(`([+-]${oneOrTwo.source})(?::(${two.source}))?`), 2);\n case \"ZZZ\":\n return offset(new RegExp(`([+-]${oneOrTwo.source})(${two.source})?`), 2);\n // we don't support ZZZZ (PST) or ZZZZZ (Pacific Standard Time) in parsing\n // because we don't have any way to figure out what they are\n case \"z\":\n return simple(/[a-z_+-/]{1,256}?/i);\n // this special-case \"token\" represents a place where a macro-token expanded into a white-space literal\n // in this case we accept any non-newline white-space\n case \" \":\n return simple(/[^\\S\\n\\r]/);\n default:\n return literal(t);\n }\n };\n\n const unit = unitate(token) || {\n invalidReason: MISSING_FTP,\n };\n\n unit.token = token;\n\n return unit;\n}\n\nconst partTypeStyleToTokenVal = {\n year: {\n \"2-digit\": \"yy\",\n numeric: \"yyyyy\",\n },\n month: {\n numeric: \"M\",\n \"2-digit\": \"MM\",\n short: \"MMM\",\n long: \"MMMM\",\n },\n day: {\n numeric: \"d\",\n \"2-digit\": \"dd\",\n },\n weekday: {\n short: \"EEE\",\n long: \"EEEE\",\n },\n dayperiod: \"a\",\n dayPeriod: \"a\",\n hour12: {\n numeric: \"h\",\n \"2-digit\": \"hh\",\n },\n hour24: {\n numeric: \"H\",\n \"2-digit\": \"HH\",\n },\n minute: {\n numeric: \"m\",\n \"2-digit\": \"mm\",\n },\n second: {\n numeric: \"s\",\n \"2-digit\": \"ss\",\n },\n timeZoneName: {\n long: \"ZZZZZ\",\n short: \"ZZZ\",\n },\n};\n\nfunction tokenForPart(part, formatOpts, resolvedOpts) {\n const { type, value } = part;\n\n if (type === \"literal\") {\n const isSpace = /^\\s+$/.test(value);\n return {\n literal: !isSpace,\n val: isSpace ? \" \" : value,\n };\n }\n\n const style = formatOpts[type];\n\n // The user might have explicitly specified hour12 or hourCycle\n // if so, respect their decision\n // if not, refer back to the resolvedOpts, which are based on the locale\n let actualType = type;\n if (type === \"hour\") {\n if (formatOpts.hour12 != null) {\n actualType = formatOpts.hour12 ? \"hour12\" : \"hour24\";\n } else if (formatOpts.hourCycle != null) {\n if (formatOpts.hourCycle === \"h11\" || formatOpts.hourCycle === \"h12\") {\n actualType = \"hour12\";\n } else {\n actualType = \"hour24\";\n }\n } else {\n // tokens only differentiate between 24 hours or not,\n // so we do not need to check hourCycle here, which is less supported anyways\n actualType = resolvedOpts.hour12 ? \"hour12\" : \"hour24\";\n }\n }\n let val = partTypeStyleToTokenVal[actualType];\n if (typeof val === \"object\") {\n val = val[style];\n }\n\n if (val) {\n return {\n literal: false,\n val,\n };\n }\n\n return undefined;\n}\n\nfunction buildRegex(units) {\n const re = units.map((u) => u.regex).reduce((f, r) => `${f}(${r.source})`, \"\");\n return [`^${re}$`, units];\n}\n\nfunction match(input, regex, handlers) {\n const matches = input.match(regex);\n\n if (matches) {\n const all = {};\n let matchIndex = 1;\n for (const i in handlers) {\n if (hasOwnProperty(handlers, i)) {\n const h = handlers[i],\n groups = h.groups ? h.groups + 1 : 1;\n if (!h.literal && h.token) {\n all[h.token.val[0]] = h.deser(matches.slice(matchIndex, matchIndex + groups));\n }\n matchIndex += groups;\n }\n }\n return [matches, all];\n } else {\n return [matches, {}];\n }\n}\n\nfunction dateTimeFromMatches(matches) {\n const toField = (token) => {\n switch (token) {\n case \"S\":\n return \"millisecond\";\n case \"s\":\n return \"second\";\n case \"m\":\n return \"minute\";\n case \"h\":\n case \"H\":\n return \"hour\";\n case \"d\":\n return \"day\";\n case \"o\":\n return \"ordinal\";\n case \"L\":\n case \"M\":\n return \"month\";\n case \"y\":\n return \"year\";\n case \"E\":\n case \"c\":\n return \"weekday\";\n case \"W\":\n return \"weekNumber\";\n case \"k\":\n return \"weekYear\";\n case \"q\":\n return \"quarter\";\n default:\n return null;\n }\n };\n\n let zone = null;\n let specificOffset;\n if (!isUndefined(matches.z)) {\n zone = IANAZone.create(matches.z);\n }\n\n if (!isUndefined(matches.Z)) {\n if (!zone) {\n zone = new FixedOffsetZone(matches.Z);\n }\n specificOffset = matches.Z;\n }\n\n if (!isUndefined(matches.q)) {\n matches.M = (matches.q - 1) * 3 + 1;\n }\n\n if (!isUndefined(matches.h)) {\n if (matches.h < 12 && matches.a === 1) {\n matches.h += 12;\n } else if (matches.h === 12 && matches.a === 0) {\n matches.h = 0;\n }\n }\n\n if (matches.G === 0 && matches.y) {\n matches.y = -matches.y;\n }\n\n if (!isUndefined(matches.u)) {\n matches.S = parseMillis(matches.u);\n }\n\n const vals = Object.keys(matches).reduce((r, k) => {\n const f = toField(k);\n if (f) {\n r[f] = matches[k];\n }\n\n return r;\n }, {});\n\n return [vals, zone, specificOffset];\n}\n\nlet dummyDateTimeCache = null;\n\nfunction getDummyDateTime() {\n if (!dummyDateTimeCache) {\n dummyDateTimeCache = DateTime.fromMillis(1555555555555);\n }\n\n return dummyDateTimeCache;\n}\n\nfunction maybeExpandMacroToken(token, locale) {\n if (token.literal) {\n return token;\n }\n\n const formatOpts = Formatter.macroTokenToFormatOpts(token.val);\n const tokens = formatOptsToTokens(formatOpts, locale);\n\n if (tokens == null || tokens.includes(undefined)) {\n return token;\n }\n\n return tokens;\n}\n\nexport function expandMacroTokens(tokens, locale) {\n return Array.prototype.concat(...tokens.map((t) => maybeExpandMacroToken(t, locale)));\n}\n\n/**\n * @private\n */\n\nexport class TokenParser {\n constructor(locale, format) {\n this.locale = locale;\n this.format = format;\n this.tokens = expandMacroTokens(Formatter.parseFormat(format), locale);\n this.units = this.tokens.map((t) => unitForToken(t, locale));\n this.disqualifyingUnit = this.units.find((t) => t.invalidReason);\n\n if (!this.disqualifyingUnit) {\n const [regexString, handlers] = buildRegex(this.units);\n this.regex = RegExp(regexString, \"i\");\n this.handlers = handlers;\n }\n }\n\n explainFromTokens(input) {\n if (!this.isValid) {\n return { input, tokens: this.tokens, invalidReason: this.invalidReason };\n } else {\n const [rawMatches, matches] = match(input, this.regex, this.handlers),\n [result, zone, specificOffset] = matches\n ? dateTimeFromMatches(matches)\n : [null, null, undefined];\n if (hasOwnProperty(matches, \"a\") && hasOwnProperty(matches, \"H\")) {\n throw new ConflictingSpecificationError(\n \"Can't include meridiem when specifying 24-hour format\"\n );\n }\n return {\n input,\n tokens: this.tokens,\n regex: this.regex,\n rawMatches,\n matches,\n result,\n zone,\n specificOffset,\n };\n }\n }\n\n get isValid() {\n return !this.disqualifyingUnit;\n }\n\n get invalidReason() {\n return this.disqualifyingUnit ? this.disqualifyingUnit.invalidReason : null;\n }\n}\n\nexport function explainFromTokens(locale, input, format) {\n const parser = new TokenParser(locale, format);\n return parser.explainFromTokens(input);\n}\n\nexport function parseFromTokens(locale, input, format) {\n const { result, zone, specificOffset, invalidReason } = explainFromTokens(locale, input, format);\n return [result, zone, specificOffset, invalidReason];\n}\n\nexport function formatOptsToTokens(formatOpts, locale) {\n if (!formatOpts) {\n return null;\n }\n\n const formatter = Formatter.create(locale, formatOpts);\n const df = formatter.dtFormatter(getDummyDateTime());\n const parts = df.formatToParts();\n const resolvedOpts = df.resolvedOptions();\n return parts.map((p) => tokenForPart(p, formatOpts, resolvedOpts));\n}\n", "import Duration from \"./duration.js\";\nimport Interval from \"./interval.js\";\nimport Settings from \"./settings.js\";\nimport Info from \"./info.js\";\nimport Formatter from \"./impl/formatter.js\";\nimport FixedOffsetZone from \"./zones/fixedOffsetZone.js\";\nimport Locale from \"./impl/locale.js\";\nimport {\n isUndefined,\n maybeArray,\n isDate,\n isNumber,\n bestBy,\n daysInMonth,\n daysInYear,\n isLeapYear,\n weeksInWeekYear,\n normalizeObject,\n roundTo,\n objToLocalTS,\n padStart,\n} from \"./impl/util.js\";\nimport { normalizeZone } from \"./impl/zoneUtil.js\";\nimport diff from \"./impl/diff.js\";\nimport { parseRFC2822Date, parseISODate, parseHTTPDate, parseSQL } from \"./impl/regexParser.js\";\nimport {\n parseFromTokens,\n explainFromTokens,\n formatOptsToTokens,\n expandMacroTokens,\n TokenParser,\n} from \"./impl/tokenParser.js\";\nimport {\n gregorianToWeek,\n weekToGregorian,\n gregorianToOrdinal,\n ordinalToGregorian,\n hasInvalidGregorianData,\n hasInvalidWeekData,\n hasInvalidOrdinalData,\n hasInvalidTimeData,\n usesLocalWeekValues,\n isoWeekdayToLocal,\n} from \"./impl/conversions.js\";\nimport * as Formats from \"./impl/formats.js\";\nimport {\n InvalidArgumentError,\n ConflictingSpecificationError,\n InvalidUnitError,\n InvalidDateTimeError,\n} from \"./errors.js\";\nimport Invalid from \"./impl/invalid.js\";\n\nconst INVALID = \"Invalid DateTime\";\nconst MAX_DATE = 8.64e15;\n\nfunction unsupportedZone(zone) {\n return new Invalid(\"unsupported zone\", `the zone \"${zone.name}\" is not supported`);\n}\n\n// we cache week data on the DT object and this intermediates the cache\n/**\n * @param {DateTime} dt\n */\nfunction possiblyCachedWeekData(dt) {\n if (dt.weekData === null) {\n dt.weekData = gregorianToWeek(dt.c);\n }\n return dt.weekData;\n}\n\n/**\n * @param {DateTime} dt\n */\nfunction possiblyCachedLocalWeekData(dt) {\n if (dt.localWeekData === null) {\n dt.localWeekData = gregorianToWeek(\n dt.c,\n dt.loc.getMinDaysInFirstWeek(),\n dt.loc.getStartOfWeek()\n );\n }\n return dt.localWeekData;\n}\n\n// clone really means, \"make a new object with these modifications\". all \"setters\" really use this\n// to create a new object while only changing some of the properties\nfunction clone(inst, alts) {\n const current = {\n ts: inst.ts,\n zone: inst.zone,\n c: inst.c,\n o: inst.o,\n loc: inst.loc,\n invalid: inst.invalid,\n };\n return new DateTime({ ...current, ...alts, old: current });\n}\n\n// find the right offset a given local time. The o input is our guess, which determines which\n// offset we'll pick in ambiguous cases (e.g. there are two 3 AMs b/c Fallback DST)\nfunction fixOffset(localTS, o, tz) {\n // Our UTC time is just a guess because our offset is just a guess\n let utcGuess = localTS - o * 60 * 1000;\n\n // Test whether the zone matches the offset for this ts\n const o2 = tz.offset(utcGuess);\n\n // If so, offset didn't change and we're done\n if (o === o2) {\n return [utcGuess, o];\n }\n\n // If not, change the ts by the difference in the offset\n utcGuess -= (o2 - o) * 60 * 1000;\n\n // If that gives us the local time we want, we're done\n const o3 = tz.offset(utcGuess);\n if (o2 === o3) {\n return [utcGuess, o2];\n }\n\n // If it's different, we're in a hole time. The offset has changed, but the we don't adjust the time\n return [localTS - Math.min(o2, o3) * 60 * 1000, Math.max(o2, o3)];\n}\n\n// convert an epoch timestamp into a calendar object with the given offset\nfunction tsToObj(ts, offset) {\n ts += offset * 60 * 1000;\n\n const d = new Date(ts);\n\n return {\n year: d.getUTCFullYear(),\n month: d.getUTCMonth() + 1,\n day: d.getUTCDate(),\n hour: d.getUTCHours(),\n minute: d.getUTCMinutes(),\n second: d.getUTCSeconds(),\n millisecond: d.getUTCMilliseconds(),\n };\n}\n\n// convert a calendar object to a epoch timestamp\nfunction objToTS(obj, offset, zone) {\n return fixOffset(objToLocalTS(obj), offset, zone);\n}\n\n// create a new DT instance by adding a duration, adjusting for DSTs\nfunction adjustTime(inst, dur) {\n const oPre = inst.o,\n year = inst.c.year + Math.trunc(dur.years),\n month = inst.c.month + Math.trunc(dur.months) + Math.trunc(dur.quarters) * 3,\n c = {\n ...inst.c,\n year,\n month,\n day:\n Math.min(inst.c.day, daysInMonth(year, month)) +\n Math.trunc(dur.days) +\n Math.trunc(dur.weeks) * 7,\n },\n millisToAdd = Duration.fromObject({\n years: dur.years - Math.trunc(dur.years),\n quarters: dur.quarters - Math.trunc(dur.quarters),\n months: dur.months - Math.trunc(dur.months),\n weeks: dur.weeks - Math.trunc(dur.weeks),\n days: dur.days - Math.trunc(dur.days),\n hours: dur.hours,\n minutes: dur.minutes,\n seconds: dur.seconds,\n milliseconds: dur.milliseconds,\n }).as(\"milliseconds\"),\n localTS = objToLocalTS(c);\n\n let [ts, o] = fixOffset(localTS, oPre, inst.zone);\n\n if (millisToAdd !== 0) {\n ts += millisToAdd;\n // that could have changed the offset by going over a DST, but we want to keep the ts the same\n o = inst.zone.offset(ts);\n }\n\n return { ts, o };\n}\n\n// helper useful in turning the results of parsing into real dates\n// by handling the zone options\nfunction parseDataToDateTime(parsed, parsedZone, opts, format, text, specificOffset) {\n const { setZone, zone } = opts;\n if ((parsed && Object.keys(parsed).length !== 0) || parsedZone) {\n const interpretationZone = parsedZone || zone,\n inst = DateTime.fromObject(parsed, {\n ...opts,\n zone: interpretationZone,\n specificOffset,\n });\n return setZone ? inst : inst.setZone(zone);\n } else {\n return DateTime.invalid(\n new Invalid(\"unparsable\", `the input \"${text}\" can't be parsed as ${format}`)\n );\n }\n}\n\n// if you want to output a technical format (e.g. RFC 2822), this helper\n// helps handle the details\nfunction toTechFormat(dt, format, allowZ = true) {\n return dt.isValid\n ? Formatter.create(Locale.create(\"en-US\"), {\n allowZ,\n forceSimple: true,\n }).formatDateTimeFromString(dt, format)\n : null;\n}\n\nfunction toISODate(o, extended) {\n const longFormat = o.c.year > 9999 || o.c.year < 0;\n let c = \"\";\n if (longFormat && o.c.year >= 0) c += \"+\";\n c += padStart(o.c.year, longFormat ? 6 : 4);\n\n if (extended) {\n c += \"-\";\n c += padStart(o.c.month);\n c += \"-\";\n c += padStart(o.c.day);\n } else {\n c += padStart(o.c.month);\n c += padStart(o.c.day);\n }\n return c;\n}\n\nfunction toISOTime(\n o,\n extended,\n suppressSeconds,\n suppressMilliseconds,\n includeOffset,\n extendedZone\n) {\n let c = padStart(o.c.hour);\n if (extended) {\n c += \":\";\n c += padStart(o.c.minute);\n if (o.c.millisecond !== 0 || o.c.second !== 0 || !suppressSeconds) {\n c += \":\";\n }\n } else {\n c += padStart(o.c.minute);\n }\n\n if (o.c.millisecond !== 0 || o.c.second !== 0 || !suppressSeconds) {\n c += padStart(o.c.second);\n\n if (o.c.millisecond !== 0 || !suppressMilliseconds) {\n c += \".\";\n c += padStart(o.c.millisecond, 3);\n }\n }\n\n if (includeOffset) {\n if (o.isOffsetFixed && o.offset === 0 && !extendedZone) {\n c += \"Z\";\n } else if (o.o < 0) {\n c += \"-\";\n c += padStart(Math.trunc(-o.o / 60));\n c += \":\";\n c += padStart(Math.trunc(-o.o % 60));\n } else {\n c += \"+\";\n c += padStart(Math.trunc(o.o / 60));\n c += \":\";\n c += padStart(Math.trunc(o.o % 60));\n }\n }\n\n if (extendedZone) {\n c += \"[\" + o.zone.ianaName + \"]\";\n }\n return c;\n}\n\n// defaults for unspecified units in the supported calendars\nconst defaultUnitValues = {\n month: 1,\n day: 1,\n hour: 0,\n minute: 0,\n second: 0,\n millisecond: 0,\n },\n defaultWeekUnitValues = {\n weekNumber: 1,\n weekday: 1,\n hour: 0,\n minute: 0,\n second: 0,\n millisecond: 0,\n },\n defaultOrdinalUnitValues = {\n ordinal: 1,\n hour: 0,\n minute: 0,\n second: 0,\n millisecond: 0,\n };\n\n// Units in the supported calendars, sorted by bigness\nconst orderedUnits = [\"year\", \"month\", \"day\", \"hour\", \"minute\", \"second\", \"millisecond\"],\n orderedWeekUnits = [\n \"weekYear\",\n \"weekNumber\",\n \"weekday\",\n \"hour\",\n \"minute\",\n \"second\",\n \"millisecond\",\n ],\n orderedOrdinalUnits = [\"year\", \"ordinal\", \"hour\", \"minute\", \"second\", \"millisecond\"];\n\n// standardize case and plurality in units\nfunction normalizeUnit(unit) {\n const normalized = {\n year: \"year\",\n years: \"year\",\n month: \"month\",\n months: \"month\",\n day: \"day\",\n days: \"day\",\n hour: \"hour\",\n hours: \"hour\",\n minute: \"minute\",\n minutes: \"minute\",\n quarter: \"quarter\",\n quarters: \"quarter\",\n second: \"second\",\n seconds: \"second\",\n millisecond: \"millisecond\",\n milliseconds: \"millisecond\",\n weekday: \"weekday\",\n weekdays: \"weekday\",\n weeknumber: \"weekNumber\",\n weeksnumber: \"weekNumber\",\n weeknumbers: \"weekNumber\",\n weekyear: \"weekYear\",\n weekyears: \"weekYear\",\n ordinal: \"ordinal\",\n }[unit.toLowerCase()];\n\n if (!normalized) throw new InvalidUnitError(unit);\n\n return normalized;\n}\n\nfunction normalizeUnitWithLocalWeeks(unit) {\n switch (unit.toLowerCase()) {\n case \"localweekday\":\n case \"localweekdays\":\n return \"localWeekday\";\n case \"localweeknumber\":\n case \"localweeknumbers\":\n return \"localWeekNumber\";\n case \"localweekyear\":\n case \"localweekyears\":\n return \"localWeekYear\";\n default:\n return normalizeUnit(unit);\n }\n}\n\n// cache offsets for zones based on the current timestamp when this function is\n// first called. When we are handling a datetime from components like (year,\n// month, day, hour) in a time zone, we need a guess about what the timezone\n// offset is so that we can convert into a UTC timestamp. One way is to find the\n// offset of now in the zone. The actual date may have a different offset (for\n// example, if we handle a date in June while we're in December in a zone that\n// observes DST), but we can check and adjust that.\n//\n// When handling many dates, calculating the offset for now every time is\n// expensive. It's just a guess, so we can cache the offset to use even if we\n// are right on a time change boundary (we'll just correct in the other\n// direction). Using a timestamp from first read is a slight optimization for\n// handling dates close to the current date, since those dates will usually be\n// in the same offset (we could set the timestamp statically, instead). We use a\n// single timestamp for all zones to make things a bit more predictable.\n//\n// This is safe for quickDT (used by local() and utc()) because we don't fill in\n// higher-order units from tsNow (as we do in fromObject, this requires that\n// offset is calculated from tsNow).\nfunction guessOffsetForZone(zone) {\n if (!zoneOffsetGuessCache[zone]) {\n if (zoneOffsetTs === undefined) {\n zoneOffsetTs = Settings.now();\n }\n\n zoneOffsetGuessCache[zone] = zone.offset(zoneOffsetTs);\n }\n return zoneOffsetGuessCache[zone];\n}\n\n// this is a dumbed down version of fromObject() that runs about 60% faster\n// but doesn't do any validation, makes a bunch of assumptions about what units\n// are present, and so on.\nfunction quickDT(obj, opts) {\n const zone = normalizeZone(opts.zone, Settings.defaultZone);\n if (!zone.isValid) {\n return DateTime.invalid(unsupportedZone(zone));\n }\n\n const loc = Locale.fromObject(opts);\n\n let ts, o;\n\n // assume we have the higher-order units\n if (!isUndefined(obj.year)) {\n for (const u of orderedUnits) {\n if (isUndefined(obj[u])) {\n obj[u] = defaultUnitValues[u];\n }\n }\n\n const invalid = hasInvalidGregorianData(obj) || hasInvalidTimeData(obj);\n if (invalid) {\n return DateTime.invalid(invalid);\n }\n\n const offsetProvis = guessOffsetForZone(zone);\n [ts, o] = objToTS(obj, offsetProvis, zone);\n } else {\n ts = Settings.now();\n }\n\n return new DateTime({ ts, zone, loc, o });\n}\n\nfunction diffRelative(start, end, opts) {\n const round = isUndefined(opts.round) ? true : opts.round,\n format = (c, unit) => {\n c = roundTo(c, round || opts.calendary ? 0 : 2, true);\n const formatter = end.loc.clone(opts).relFormatter(opts);\n return formatter.format(c, unit);\n },\n differ = (unit) => {\n if (opts.calendary) {\n if (!end.hasSame(start, unit)) {\n return end.startOf(unit).diff(start.startOf(unit), unit).get(unit);\n } else return 0;\n } else {\n return end.diff(start, unit).get(unit);\n }\n };\n\n if (opts.unit) {\n return format(differ(opts.unit), opts.unit);\n }\n\n for (const unit of opts.units) {\n const count = differ(unit);\n if (Math.abs(count) >= 1) {\n return format(count, unit);\n }\n }\n return format(start > end ? -0 : 0, opts.units[opts.units.length - 1]);\n}\n\nfunction lastOpts(argList) {\n let opts = {},\n args;\n if (argList.length > 0 && typeof argList[argList.length - 1] === \"object\") {\n opts = argList[argList.length - 1];\n args = Array.from(argList).slice(0, argList.length - 1);\n } else {\n args = Array.from(argList);\n }\n return [opts, args];\n}\n\n/**\n * Timestamp to use for cached zone offset guesses (exposed for test)\n */\nlet zoneOffsetTs;\n/**\n * Cache for zone offset guesses (exposed for test).\n *\n * This optimizes quickDT via guessOffsetForZone to avoid repeated calls of\n * zone.offset().\n */\nlet zoneOffsetGuessCache = {};\n\n/**\n * A DateTime is an immutable data structure representing a specific date and time and accompanying methods. It contains class and instance methods for creating, parsing, interrogating, transforming, and formatting them.\n *\n * A DateTime comprises of:\n * * A timestamp. Each DateTime instance refers to a specific millisecond of the Unix epoch.\n * * A time zone. Each instance is considered in the context of a specific zone (by default the local system's zone).\n * * Configuration properties that effect how output strings are formatted, such as `locale`, `numberingSystem`, and `outputCalendar`.\n *\n * Here is a brief overview of the most commonly used functionality it provides:\n *\n * * **Creation**: To create a DateTime from its components, use one of its factory class methods: {@link DateTime.local}, {@link DateTime.utc}, and (most flexibly) {@link DateTime.fromObject}. To create one from a standard string format, use {@link DateTime.fromISO}, {@link DateTime.fromHTTP}, and {@link DateTime.fromRFC2822}. To create one from a custom string format, use {@link DateTime.fromFormat}. To create one from a native JS date, use {@link DateTime.fromJSDate}.\n * * **Gregorian calendar and time**: To examine the Gregorian properties of a DateTime individually (i.e as opposed to collectively through {@link DateTime#toObject}), use the {@link DateTime#year}, {@link DateTime#month},\n * {@link DateTime#day}, {@link DateTime#hour}, {@link DateTime#minute}, {@link DateTime#second}, {@link DateTime#millisecond} accessors.\n * * **Week calendar**: For ISO week calendar attributes, see the {@link DateTime#weekYear}, {@link DateTime#weekNumber}, and {@link DateTime#weekday} accessors.\n * * **Configuration** See the {@link DateTime#locale} and {@link DateTime#numberingSystem} accessors.\n * * **Transformation**: To transform the DateTime into other DateTimes, use {@link DateTime#set}, {@link DateTime#reconfigure}, {@link DateTime#setZone}, {@link DateTime#setLocale}, {@link DateTime.plus}, {@link DateTime#minus}, {@link DateTime#endOf}, {@link DateTime#startOf}, {@link DateTime#toUTC}, and {@link DateTime#toLocal}.\n * * **Output**: To convert the DateTime to other representations, use the {@link DateTime#toRelative}, {@link DateTime#toRelativeCalendar}, {@link DateTime#toJSON}, {@link DateTime#toISO}, {@link DateTime#toHTTP}, {@link DateTime#toObject}, {@link DateTime#toRFC2822}, {@link DateTime#toString}, {@link DateTime#toLocaleString}, {@link DateTime#toFormat}, {@link DateTime#toMillis} and {@link DateTime#toJSDate}.\n *\n * There's plenty others documented below. In addition, for more information on subtler topics like internationalization, time zones, alternative calendars, validity, and so on, see the external documentation.\n */\nexport default class DateTime {\n /**\n * @access private\n */\n constructor(config) {\n const zone = config.zone || Settings.defaultZone;\n\n let invalid =\n config.invalid ||\n (Number.isNaN(config.ts) ? new Invalid(\"invalid input\") : null) ||\n (!zone.isValid ? unsupportedZone(zone) : null);\n /**\n * @access private\n */\n this.ts = isUndefined(config.ts) ? Settings.now() : config.ts;\n\n let c = null,\n o = null;\n if (!invalid) {\n const unchanged = config.old && config.old.ts === this.ts && config.old.zone.equals(zone);\n\n if (unchanged) {\n [c, o] = [config.old.c, config.old.o];\n } else {\n // If an offset has been passed and we have not been called from\n // clone(), we can trust it and avoid the offset calculation.\n const ot = isNumber(config.o) && !config.old ? config.o : zone.offset(this.ts);\n c = tsToObj(this.ts, ot);\n invalid = Number.isNaN(c.year) ? new Invalid(\"invalid input\") : null;\n c = invalid ? null : c;\n o = invalid ? null : ot;\n }\n }\n\n /**\n * @access private\n */\n this._zone = zone;\n /**\n * @access private\n */\n this.loc = config.loc || Locale.create();\n /**\n * @access private\n */\n this.invalid = invalid;\n /**\n * @access private\n */\n this.weekData = null;\n /**\n * @access private\n */\n this.localWeekData = null;\n /**\n * @access private\n */\n this.c = c;\n /**\n * @access private\n */\n this.o = o;\n /**\n * @access private\n */\n this.isLuxonDateTime = true;\n }\n\n // CONSTRUCT\n\n /**\n * Create a DateTime for the current instant, in the system's time zone.\n *\n * Use Settings to override these default values if needed.\n * @example DateTime.now().toISO() //~> now in the ISO format\n * @return {DateTime}\n */\n static now() {\n return new DateTime({});\n }\n\n /**\n * Create a local DateTime\n * @param {number} [year] - The calendar year. If omitted (as in, call `local()` with no arguments), the current time will be used\n * @param {number} [month=1] - The month, 1-indexed\n * @param {number} [day=1] - The day of the month, 1-indexed\n * @param {number} [hour=0] - The hour of the day, in 24-hour time\n * @param {number} [minute=0] - The minute of the hour, meaning a number between 0 and 59\n * @param {number} [second=0] - The second of the minute, meaning a number between 0 and 59\n * @param {number} [millisecond=0] - The millisecond of the second, meaning a number between 0 and 999\n * @example DateTime.local() //~> now\n * @example DateTime.local({ zone: \"America/New_York\" }) //~> now, in US east coast time\n * @example DateTime.local(2017) //~> 2017-01-01T00:00:00\n * @example DateTime.local(2017, 3) //~> 2017-03-01T00:00:00\n * @example DateTime.local(2017, 3, 12, { locale: \"fr\" }) //~> 2017-03-12T00:00:00, with a French locale\n * @example DateTime.local(2017, 3, 12, 5) //~> 2017-03-12T05:00:00\n * @example DateTime.local(2017, 3, 12, 5, { zone: \"utc\" }) //~> 2017-03-12T05:00:00, in UTC\n * @example DateTime.local(2017, 3, 12, 5, 45) //~> 2017-03-12T05:45:00\n * @example DateTime.local(2017, 3, 12, 5, 45, 10) //~> 2017-03-12T05:45:10\n * @example DateTime.local(2017, 3, 12, 5, 45, 10, 765) //~> 2017-03-12T05:45:10.765\n * @return {DateTime}\n */\n static local() {\n const [opts, args] = lastOpts(arguments),\n [year, month, day, hour, minute, second, millisecond] = args;\n return quickDT({ year, month, day, hour, minute, second, millisecond }, opts);\n }\n\n /**\n * Create a DateTime in UTC\n * @param {number} [year] - The calendar year. If omitted (as in, call `utc()` with no arguments), the current time will be used\n * @param {number} [month=1] - The month, 1-indexed\n * @param {number} [day=1] - The day of the month\n * @param {number} [hour=0] - The hour of the day, in 24-hour time\n * @param {number} [minute=0] - The minute of the hour, meaning a number between 0 and 59\n * @param {number} [second=0] - The second of the minute, meaning a number between 0 and 59\n * @param {number} [millisecond=0] - The millisecond of the second, meaning a number between 0 and 999\n * @param {Object} options - configuration options for the DateTime\n * @param {string} [options.locale] - a locale to set on the resulting DateTime instance\n * @param {string} [options.outputCalendar] - the output calendar to set on the resulting DateTime instance\n * @param {string} [options.numberingSystem] - the numbering system to set on the resulting DateTime instance\n * @param {string} [options.weekSettings] - the week settings to set on the resulting DateTime instance\n * @example DateTime.utc() //~> now\n * @example DateTime.utc(2017) //~> 2017-01-01T00:00:00Z\n * @example DateTime.utc(2017, 3) //~> 2017-03-01T00:00:00Z\n * @example DateTime.utc(2017, 3, 12) //~> 2017-03-12T00:00:00Z\n * @example DateTime.utc(2017, 3, 12, 5) //~> 2017-03-12T05:00:00Z\n * @example DateTime.utc(2017, 3, 12, 5, 45) //~> 2017-03-12T05:45:00Z\n * @example DateTime.utc(2017, 3, 12, 5, 45, { locale: \"fr\" }) //~> 2017-03-12T05:45:00Z with a French locale\n * @example DateTime.utc(2017, 3, 12, 5, 45, 10) //~> 2017-03-12T05:45:10Z\n * @example DateTime.utc(2017, 3, 12, 5, 45, 10, 765, { locale: \"fr\" }) //~> 2017-03-12T05:45:10.765Z with a French locale\n * @return {DateTime}\n */\n static utc() {\n const [opts, args] = lastOpts(arguments),\n [year, month, day, hour, minute, second, millisecond] = args;\n\n opts.zone = FixedOffsetZone.utcInstance;\n return quickDT({ year, month, day, hour, minute, second, millisecond }, opts);\n }\n\n /**\n * Create a DateTime from a JavaScript Date object. Uses the default zone.\n * @param {Date} date - a JavaScript Date object\n * @param {Object} options - configuration options for the DateTime\n * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into\n * @return {DateTime}\n */\n static fromJSDate(date, options = {}) {\n const ts = isDate(date) ? date.valueOf() : NaN;\n if (Number.isNaN(ts)) {\n return DateTime.invalid(\"invalid input\");\n }\n\n const zoneToUse = normalizeZone(options.zone, Settings.defaultZone);\n if (!zoneToUse.isValid) {\n return DateTime.invalid(unsupportedZone(zoneToUse));\n }\n\n return new DateTime({\n ts: ts,\n zone: zoneToUse,\n loc: Locale.fromObject(options),\n });\n }\n\n /**\n * Create a DateTime from a number of milliseconds since the epoch (meaning since 1 January 1970 00:00:00 UTC). Uses the default zone.\n * @param {number} milliseconds - a number of milliseconds since 1970 UTC\n * @param {Object} options - configuration options for the DateTime\n * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into\n * @param {string} [options.locale] - a locale to set on the resulting DateTime instance\n * @param {string} options.outputCalendar - the output calendar to set on the resulting DateTime instance\n * @param {string} options.numberingSystem - the numbering system to set on the resulting DateTime instance\n * @param {string} options.weekSettings - the week settings to set on the resulting DateTime instance\n * @return {DateTime}\n */\n static fromMillis(milliseconds, options = {}) {\n if (!isNumber(milliseconds)) {\n throw new InvalidArgumentError(\n `fromMillis requires a numerical input, but received a ${typeof milliseconds} with value ${milliseconds}`\n );\n } else if (milliseconds < -MAX_DATE || milliseconds > MAX_DATE) {\n // this isn't perfect because we can still end up out of range because of additional shifting, but it's a start\n return DateTime.invalid(\"Timestamp out of range\");\n } else {\n return new DateTime({\n ts: milliseconds,\n zone: normalizeZone(options.zone, Settings.defaultZone),\n loc: Locale.fromObject(options),\n });\n }\n }\n\n /**\n * Create a DateTime from a number of seconds since the epoch (meaning since 1 January 1970 00:00:00 UTC). Uses the default zone.\n * @param {number} seconds - a number of seconds since 1970 UTC\n * @param {Object} options - configuration options for the DateTime\n * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into\n * @param {string} [options.locale] - a locale to set on the resulting DateTime instance\n * @param {string} options.outputCalendar - the output calendar to set on the resulting DateTime instance\n * @param {string} options.numberingSystem - the numbering system to set on the resulting DateTime instance\n * @param {string} options.weekSettings - the week settings to set on the resulting DateTime instance\n * @return {DateTime}\n */\n static fromSeconds(seconds, options = {}) {\n if (!isNumber(seconds)) {\n throw new InvalidArgumentError(\"fromSeconds requires a numerical input\");\n } else {\n return new DateTime({\n ts: seconds * 1000,\n zone: normalizeZone(options.zone, Settings.defaultZone),\n loc: Locale.fromObject(options),\n });\n }\n }\n\n /**\n * Create a DateTime from a JavaScript object with keys like 'year' and 'hour' with reasonable defaults.\n * @param {Object} obj - the object to create the DateTime from\n * @param {number} obj.year - a year, such as 1987\n * @param {number} obj.month - a month, 1-12\n * @param {number} obj.day - a day of the month, 1-31, depending on the month\n * @param {number} obj.ordinal - day of the year, 1-365 or 366\n * @param {number} obj.weekYear - an ISO week year\n * @param {number} obj.weekNumber - an ISO week number, between 1 and 52 or 53, depending on the year\n * @param {number} obj.weekday - an ISO weekday, 1-7, where 1 is Monday and 7 is Sunday\n * @param {number} obj.localWeekYear - a week year, according to the locale\n * @param {number} obj.localWeekNumber - a week number, between 1 and 52 or 53, depending on the year, according to the locale\n * @param {number} obj.localWeekday - a weekday, 1-7, where 1 is the first and 7 is the last day of the week, according to the locale\n * @param {number} obj.hour - hour of the day, 0-23\n * @param {number} obj.minute - minute of the hour, 0-59\n * @param {number} obj.second - second of the minute, 0-59\n * @param {number} obj.millisecond - millisecond of the second, 0-999\n * @param {Object} opts - options for creating this DateTime\n * @param {string|Zone} [opts.zone='local'] - interpret the numbers in the context of a particular zone. Can take any value taken as the first argument to setZone()\n * @param {string} [opts.locale='system\\'s locale'] - a locale to set on the resulting DateTime instance\n * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance\n * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance\n * @param {string} opts.weekSettings - the week settings to set on the resulting DateTime instance\n * @example DateTime.fromObject({ year: 1982, month: 5, day: 25}).toISODate() //=> '1982-05-25'\n * @example DateTime.fromObject({ year: 1982 }).toISODate() //=> '1982-01-01'\n * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }) //~> today at 10:26:06\n * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'utc' }),\n * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'local' })\n * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'America/New_York' })\n * @example DateTime.fromObject({ weekYear: 2016, weekNumber: 2, weekday: 3 }).toISODate() //=> '2016-01-13'\n * @example DateTime.fromObject({ localWeekYear: 2022, localWeekNumber: 1, localWeekday: 1 }, { locale: \"en-US\" }).toISODate() //=> '2021-12-26'\n * @return {DateTime}\n */\n static fromObject(obj, opts = {}) {\n obj = obj || {};\n const zoneToUse = normalizeZone(opts.zone, Settings.defaultZone);\n if (!zoneToUse.isValid) {\n return DateTime.invalid(unsupportedZone(zoneToUse));\n }\n\n const loc = Locale.fromObject(opts);\n const normalized = normalizeObject(obj, normalizeUnitWithLocalWeeks);\n const { minDaysInFirstWeek, startOfWeek } = usesLocalWeekValues(normalized, loc);\n\n const tsNow = Settings.now(),\n offsetProvis = !isUndefined(opts.specificOffset)\n ? opts.specificOffset\n : zoneToUse.offset(tsNow),\n containsOrdinal = !isUndefined(normalized.ordinal),\n containsGregorYear = !isUndefined(normalized.year),\n containsGregorMD = !isUndefined(normalized.month) || !isUndefined(normalized.day),\n containsGregor = containsGregorYear || containsGregorMD,\n definiteWeekDef = normalized.weekYear || normalized.weekNumber;\n\n // cases:\n // just a weekday -> this week's instance of that weekday, no worries\n // (gregorian data or ordinal) + (weekYear or weekNumber) -> error\n // (gregorian month or day) + ordinal -> error\n // otherwise just use weeks or ordinals or gregorian, depending on what's specified\n\n if ((containsGregor || containsOrdinal) && definiteWeekDef) {\n throw new ConflictingSpecificationError(\n \"Can't mix weekYear/weekNumber units with year/month/day or ordinals\"\n );\n }\n\n if (containsGregorMD && containsOrdinal) {\n throw new ConflictingSpecificationError(\"Can't mix ordinal dates with month/day\");\n }\n\n const useWeekData = definiteWeekDef || (normalized.weekday && !containsGregor);\n\n // configure ourselves to deal with gregorian dates or week stuff\n let units,\n defaultValues,\n objNow = tsToObj(tsNow, offsetProvis);\n if (useWeekData) {\n units = orderedWeekUnits;\n defaultValues = defaultWeekUnitValues;\n objNow = gregorianToWeek(objNow, minDaysInFirstWeek, startOfWeek);\n } else if (containsOrdinal) {\n units = orderedOrdinalUnits;\n defaultValues = defaultOrdinalUnitValues;\n objNow = gregorianToOrdinal(objNow);\n } else {\n units = orderedUnits;\n defaultValues = defaultUnitValues;\n }\n\n // set default values for missing stuff\n let foundFirst = false;\n for (const u of units) {\n const v = normalized[u];\n if (!isUndefined(v)) {\n foundFirst = true;\n } else if (foundFirst) {\n normalized[u] = defaultValues[u];\n } else {\n normalized[u] = objNow[u];\n }\n }\n\n // make sure the values we have are in range\n const higherOrderInvalid = useWeekData\n ? hasInvalidWeekData(normalized, minDaysInFirstWeek, startOfWeek)\n : containsOrdinal\n ? hasInvalidOrdinalData(normalized)\n : hasInvalidGregorianData(normalized),\n invalid = higherOrderInvalid || hasInvalidTimeData(normalized);\n\n if (invalid) {\n return DateTime.invalid(invalid);\n }\n\n // compute the actual time\n const gregorian = useWeekData\n ? weekToGregorian(normalized, minDaysInFirstWeek, startOfWeek)\n : containsOrdinal\n ? ordinalToGregorian(normalized)\n : normalized,\n [tsFinal, offsetFinal] = objToTS(gregorian, offsetProvis, zoneToUse),\n inst = new DateTime({\n ts: tsFinal,\n zone: zoneToUse,\n o: offsetFinal,\n loc,\n });\n\n // gregorian data + weekday serves only to validate\n if (normalized.weekday && containsGregor && obj.weekday !== inst.weekday) {\n return DateTime.invalid(\n \"mismatched weekday\",\n `you can't specify both a weekday of ${normalized.weekday} and a date of ${inst.toISO()}`\n );\n }\n\n if (!inst.isValid) {\n return DateTime.invalid(inst.invalid);\n }\n\n return inst;\n }\n\n /**\n * Create a DateTime from an ISO 8601 string\n * @param {string} text - the ISO string\n * @param {Object} opts - options to affect the creation\n * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the time to this zone\n * @param {boolean} [opts.setZone=false] - override the zone with a fixed-offset zone specified in the string itself, if it specifies one\n * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance\n * @param {string} [opts.outputCalendar] - the output calendar to set on the resulting DateTime instance\n * @param {string} [opts.numberingSystem] - the numbering system to set on the resulting DateTime instance\n * @param {string} [opts.weekSettings] - the week settings to set on the resulting DateTime instance\n * @example DateTime.fromISO('2016-05-25T09:08:34.123')\n * @example DateTime.fromISO('2016-05-25T09:08:34.123+06:00')\n * @example DateTime.fromISO('2016-05-25T09:08:34.123+06:00', {setZone: true})\n * @example DateTime.fromISO('2016-05-25T09:08:34.123', {zone: 'utc'})\n * @example DateTime.fromISO('2016-W05-4')\n * @return {DateTime}\n */\n static fromISO(text, opts = {}) {\n const [vals, parsedZone] = parseISODate(text);\n return parseDataToDateTime(vals, parsedZone, opts, \"ISO 8601\", text);\n }\n\n /**\n * Create a DateTime from an RFC 2822 string\n * @param {string} text - the RFC 2822 string\n * @param {Object} opts - options to affect the creation\n * @param {string|Zone} [opts.zone='local'] - convert the time to this zone. Since the offset is always specified in the string itself, this has no effect on the interpretation of string, merely the zone the resulting DateTime is expressed in.\n * @param {boolean} [opts.setZone=false] - override the zone with a fixed-offset zone specified in the string itself, if it specifies one\n * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance\n * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance\n * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance\n * @param {string} opts.weekSettings - the week settings to set on the resulting DateTime instance\n * @example DateTime.fromRFC2822('25 Nov 2016 13:23:12 GMT')\n * @example DateTime.fromRFC2822('Fri, 25 Nov 2016 13:23:12 +0600')\n * @example DateTime.fromRFC2822('25 Nov 2016 13:23 Z')\n * @return {DateTime}\n */\n static fromRFC2822(text, opts = {}) {\n const [vals, parsedZone] = parseRFC2822Date(text);\n return parseDataToDateTime(vals, parsedZone, opts, \"RFC 2822\", text);\n }\n\n /**\n * Create a DateTime from an HTTP header date\n * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1\n * @param {string} text - the HTTP header date\n * @param {Object} opts - options to affect the creation\n * @param {string|Zone} [opts.zone='local'] - convert the time to this zone. Since HTTP dates are always in UTC, this has no effect on the interpretation of string, merely the zone the resulting DateTime is expressed in.\n * @param {boolean} [opts.setZone=false] - override the zone with the fixed-offset zone specified in the string. For HTTP dates, this is always UTC, so this option is equivalent to setting the `zone` option to 'utc', but this option is included for consistency with similar methods.\n * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance\n * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance\n * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance\n * @param {string} opts.weekSettings - the week settings to set on the resulting DateTime instance\n * @example DateTime.fromHTTP('Sun, 06 Nov 1994 08:49:37 GMT')\n * @example DateTime.fromHTTP('Sunday, 06-Nov-94 08:49:37 GMT')\n * @example DateTime.fromHTTP('Sun Nov 6 08:49:37 1994')\n * @return {DateTime}\n */\n static fromHTTP(text, opts = {}) {\n const [vals, parsedZone] = parseHTTPDate(text);\n return parseDataToDateTime(vals, parsedZone, opts, \"HTTP\", opts);\n }\n\n /**\n * Create a DateTime from an input string and format string.\n * Defaults to en-US if no locale has been specified, regardless of the system's locale. For a table of tokens and their interpretations, see [here](https://moment.github.io/luxon/#/parsing?id=table-of-tokens).\n * @param {string} text - the string to parse\n * @param {string} fmt - the format the string is expected to be in (see the link below for the formats)\n * @param {Object} opts - options to affect the creation\n * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the DateTime to this zone\n * @param {boolean} [opts.setZone=false] - override the zone with a zone specified in the string itself, if it specifies one\n * @param {string} [opts.locale='en-US'] - a locale string to use when parsing. Will also set the DateTime to this locale\n * @param {string} opts.numberingSystem - the numbering system to use when parsing. Will also set the resulting DateTime to this numbering system\n * @param {string} opts.weekSettings - the week settings to set on the resulting DateTime instance\n * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance\n * @return {DateTime}\n */\n static fromFormat(text, fmt, opts = {}) {\n if (isUndefined(text) || isUndefined(fmt)) {\n throw new InvalidArgumentError(\"fromFormat requires an input string and a format\");\n }\n\n const { locale = null, numberingSystem = null } = opts,\n localeToUse = Locale.fromOpts({\n locale,\n numberingSystem,\n defaultToEN: true,\n }),\n [vals, parsedZone, specificOffset, invalid] = parseFromTokens(localeToUse, text, fmt);\n if (invalid) {\n return DateTime.invalid(invalid);\n } else {\n return parseDataToDateTime(vals, parsedZone, opts, `format ${fmt}`, text, specificOffset);\n }\n }\n\n /**\n * @deprecated use fromFormat instead\n */\n static fromString(text, fmt, opts = {}) {\n return DateTime.fromFormat(text, fmt, opts);\n }\n\n /**\n * Create a DateTime from a SQL date, time, or datetime\n * Defaults to en-US if no locale has been specified, regardless of the system's locale\n * @param {string} text - the string to parse\n * @param {Object} opts - options to affect the creation\n * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the DateTime to this zone\n * @param {boolean} [opts.setZone=false] - override the zone with a zone specified in the string itself, if it specifies one\n * @param {string} [opts.locale='en-US'] - a locale string to use when parsing. Will also set the DateTime to this locale\n * @param {string} opts.numberingSystem - the numbering system to use when parsing. Will also set the resulting DateTime to this numbering system\n * @param {string} opts.weekSettings - the week settings to set on the resulting DateTime instance\n * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance\n * @example DateTime.fromSQL('2017-05-15')\n * @example DateTime.fromSQL('2017-05-15 09:12:34')\n * @example DateTime.fromSQL('2017-05-15 09:12:34.342')\n * @example DateTime.fromSQL('2017-05-15 09:12:34.342+06:00')\n * @example DateTime.fromSQL('2017-05-15 09:12:34.342 America/Los_Angeles')\n * @example DateTime.fromSQL('2017-05-15 09:12:34.342 America/Los_Angeles', { setZone: true })\n * @example DateTime.fromSQL('2017-05-15 09:12:34.342', { zone: 'America/Los_Angeles' })\n * @example DateTime.fromSQL('09:12:34.342')\n * @return {DateTime}\n */\n static fromSQL(text, opts = {}) {\n const [vals, parsedZone] = parseSQL(text);\n return parseDataToDateTime(vals, parsedZone, opts, \"SQL\", text);\n }\n\n /**\n * Create an invalid DateTime.\n * @param {string} reason - simple string of why this DateTime is invalid. Should not contain parameters or anything else data-dependent.\n * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information\n * @return {DateTime}\n */\n static invalid(reason, explanation = null) {\n if (!reason) {\n throw new InvalidArgumentError(\"need to specify a reason the DateTime is invalid\");\n }\n\n const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation);\n\n if (Settings.throwOnInvalid) {\n throw new InvalidDateTimeError(invalid);\n } else {\n return new DateTime({ invalid });\n }\n }\n\n /**\n * Check if an object is an instance of DateTime. Works across context boundaries\n * @param {object} o\n * @return {boolean}\n */\n static isDateTime(o) {\n return (o && o.isLuxonDateTime) || false;\n }\n\n /**\n * Produce the format string for a set of options\n * @param formatOpts\n * @param localeOpts\n * @returns {string}\n */\n static parseFormatForOpts(formatOpts, localeOpts = {}) {\n const tokenList = formatOptsToTokens(formatOpts, Locale.fromObject(localeOpts));\n return !tokenList ? null : tokenList.map((t) => (t ? t.val : null)).join(\"\");\n }\n\n /**\n * Produce the the fully expanded format token for the locale\n * Does NOT quote characters, so quoted tokens will not round trip correctly\n * @param fmt\n * @param localeOpts\n * @returns {string}\n */\n static expandFormat(fmt, localeOpts = {}) {\n const expanded = expandMacroTokens(Formatter.parseFormat(fmt), Locale.fromObject(localeOpts));\n return expanded.map((t) => t.val).join(\"\");\n }\n\n static resetCache() {\n zoneOffsetTs = undefined;\n zoneOffsetGuessCache = {};\n }\n\n // INFO\n\n /**\n * Get the value of unit.\n * @param {string} unit - a unit such as 'minute' or 'day'\n * @example DateTime.local(2017, 7, 4).get('month'); //=> 7\n * @example DateTime.local(2017, 7, 4).get('day'); //=> 4\n * @return {number}\n */\n get(unit) {\n return this[unit];\n }\n\n /**\n * Returns whether the DateTime is valid. Invalid DateTimes occur when:\n * * The DateTime was created from invalid calendar information, such as the 13th month or February 30\n * * The DateTime was created by an operation on another invalid date\n * @type {boolean}\n */\n get isValid() {\n return this.invalid === null;\n }\n\n /**\n * Returns an error code if this DateTime is invalid, or null if the DateTime is valid\n * @type {string}\n */\n get invalidReason() {\n return this.invalid ? this.invalid.reason : null;\n }\n\n /**\n * Returns an explanation of why this DateTime became invalid, or null if the DateTime is valid\n * @type {string}\n */\n get invalidExplanation() {\n return this.invalid ? this.invalid.explanation : null;\n }\n\n /**\n * Get the locale of a DateTime, such 'en-GB'. The locale is used when formatting the DateTime\n *\n * @type {string}\n */\n get locale() {\n return this.isValid ? this.loc.locale : null;\n }\n\n /**\n * Get the numbering system of a DateTime, such 'beng'. The numbering system is used when formatting the DateTime\n *\n * @type {string}\n */\n get numberingSystem() {\n return this.isValid ? this.loc.numberingSystem : null;\n }\n\n /**\n * Get the output calendar of a DateTime, such 'islamic'. The output calendar is used when formatting the DateTime\n *\n * @type {string}\n */\n get outputCalendar() {\n return this.isValid ? this.loc.outputCalendar : null;\n }\n\n /**\n * Get the time zone associated with this DateTime.\n * @type {Zone}\n */\n get zone() {\n return this._zone;\n }\n\n /**\n * Get the name of the time zone.\n * @type {string}\n */\n get zoneName() {\n return this.isValid ? this.zone.name : null;\n }\n\n /**\n * Get the year\n * @example DateTime.local(2017, 5, 25).year //=> 2017\n * @type {number}\n */\n get year() {\n return this.isValid ? this.c.year : NaN;\n }\n\n /**\n * Get the quarter\n * @example DateTime.local(2017, 5, 25).quarter //=> 2\n * @type {number}\n */\n get quarter() {\n return this.isValid ? Math.ceil(this.c.month / 3) : NaN;\n }\n\n /**\n * Get the month (1-12).\n * @example DateTime.local(2017, 5, 25).month //=> 5\n * @type {number}\n */\n get month() {\n return this.isValid ? this.c.month : NaN;\n }\n\n /**\n * Get the day of the month (1-30ish).\n * @example DateTime.local(2017, 5, 25).day //=> 25\n * @type {number}\n */\n get day() {\n return this.isValid ? this.c.day : NaN;\n }\n\n /**\n * Get the hour of the day (0-23).\n * @example DateTime.local(2017, 5, 25, 9).hour //=> 9\n * @type {number}\n */\n get hour() {\n return this.isValid ? this.c.hour : NaN;\n }\n\n /**\n * Get the minute of the hour (0-59).\n * @example DateTime.local(2017, 5, 25, 9, 30).minute //=> 30\n * @type {number}\n */\n get minute() {\n return this.isValid ? this.c.minute : NaN;\n }\n\n /**\n * Get the second of the minute (0-59).\n * @example DateTime.local(2017, 5, 25, 9, 30, 52).second //=> 52\n * @type {number}\n */\n get second() {\n return this.isValid ? this.c.second : NaN;\n }\n\n /**\n * Get the millisecond of the second (0-999).\n * @example DateTime.local(2017, 5, 25, 9, 30, 52, 654).millisecond //=> 654\n * @type {number}\n */\n get millisecond() {\n return this.isValid ? this.c.millisecond : NaN;\n }\n\n /**\n * Get the week year\n * @see https://en.wikipedia.org/wiki/ISO_week_date\n * @example DateTime.local(2014, 12, 31).weekYear //=> 2015\n * @type {number}\n */\n get weekYear() {\n return this.isValid ? possiblyCachedWeekData(this).weekYear : NaN;\n }\n\n /**\n * Get the week number of the week year (1-52ish).\n * @see https://en.wikipedia.org/wiki/ISO_week_date\n * @example DateTime.local(2017, 5, 25).weekNumber //=> 21\n * @type {number}\n */\n get weekNumber() {\n return this.isValid ? possiblyCachedWeekData(this).weekNumber : NaN;\n }\n\n /**\n * Get the day of the week.\n * 1 is Monday and 7 is Sunday\n * @see https://en.wikipedia.org/wiki/ISO_week_date\n * @example DateTime.local(2014, 11, 31).weekday //=> 4\n * @type {number}\n */\n get weekday() {\n return this.isValid ? possiblyCachedWeekData(this).weekday : NaN;\n }\n\n /**\n * Returns true if this date is on a weekend according to the locale, false otherwise\n * @returns {boolean}\n */\n get isWeekend() {\n return this.isValid && this.loc.getWeekendDays().includes(this.weekday);\n }\n\n /**\n * Get the day of the week according to the locale.\n * 1 is the first day of the week and 7 is the last day of the week.\n * If the locale assigns Sunday as the first day of the week, then a date which is a Sunday will return 1,\n * @returns {number}\n */\n get localWeekday() {\n return this.isValid ? possiblyCachedLocalWeekData(this).weekday : NaN;\n }\n\n /**\n * Get the week number of the week year according to the locale. Different locales assign week numbers differently,\n * because the week can start on different days of the week (see localWeekday) and because a different number of days\n * is required for a week to count as the first week of a year.\n * @returns {number}\n */\n get localWeekNumber() {\n return this.isValid ? possiblyCachedLocalWeekData(this).weekNumber : NaN;\n }\n\n /**\n * Get the week year according to the locale. Different locales assign week numbers (and therefor week years)\n * differently, see localWeekNumber.\n * @returns {number}\n */\n get localWeekYear() {\n return this.isValid ? possiblyCachedLocalWeekData(this).weekYear : NaN;\n }\n\n /**\n * Get the ordinal (meaning the day of the year)\n * @example DateTime.local(2017, 5, 25).ordinal //=> 145\n * @type {number|DateTime}\n */\n get ordinal() {\n return this.isValid ? gregorianToOrdinal(this.c).ordinal : NaN;\n }\n\n /**\n * Get the human readable short month name, such as 'Oct'.\n * Defaults to the system's locale if no locale has been specified\n * @example DateTime.local(2017, 10, 30).monthShort //=> Oct\n * @type {string}\n */\n get monthShort() {\n return this.isValid ? Info.months(\"short\", { locObj: this.loc })[this.month - 1] : null;\n }\n\n /**\n * Get the human readable long month name, such as 'October'.\n * Defaults to the system's locale if no locale has been specified\n * @example DateTime.local(2017, 10, 30).monthLong //=> October\n * @type {string}\n */\n get monthLong() {\n return this.isValid ? Info.months(\"long\", { locObj: this.loc })[this.month - 1] : null;\n }\n\n /**\n * Get the human readable short weekday, such as 'Mon'.\n * Defaults to the system's locale if no locale has been specified\n * @example DateTime.local(2017, 10, 30).weekdayShort //=> Mon\n * @type {string}\n */\n get weekdayShort() {\n return this.isValid ? Info.weekdays(\"short\", { locObj: this.loc })[this.weekday - 1] : null;\n }\n\n /**\n * Get the human readable long weekday, such as 'Monday'.\n * Defaults to the system's locale if no locale has been specified\n * @example DateTime.local(2017, 10, 30).weekdayLong //=> Monday\n * @type {string}\n */\n get weekdayLong() {\n return this.isValid ? Info.weekdays(\"long\", { locObj: this.loc })[this.weekday - 1] : null;\n }\n\n /**\n * Get the UTC offset of this DateTime in minutes\n * @example DateTime.now().offset //=> -240\n * @example DateTime.utc().offset //=> 0\n * @type {number}\n */\n get offset() {\n return this.isValid ? +this.o : NaN;\n }\n\n /**\n * Get the short human name for the zone's current offset, for example \"EST\" or \"EDT\".\n * Defaults to the system's locale if no locale has been specified\n * @type {string}\n */\n get offsetNameShort() {\n if (this.isValid) {\n return this.zone.offsetName(this.ts, {\n format: \"short\",\n locale: this.locale,\n });\n } else {\n return null;\n }\n }\n\n /**\n * Get the long human name for the zone's current offset, for example \"Eastern Standard Time\" or \"Eastern Daylight Time\".\n * Defaults to the system's locale if no locale has been specified\n * @type {string}\n */\n get offsetNameLong() {\n if (this.isValid) {\n return this.zone.offsetName(this.ts, {\n format: \"long\",\n locale: this.locale,\n });\n } else {\n return null;\n }\n }\n\n /**\n * Get whether this zone's offset ever changes, as in a DST.\n * @type {boolean}\n */\n get isOffsetFixed() {\n return this.isValid ? this.zone.isUniversal : null;\n }\n\n /**\n * Get whether the DateTime is in a DST.\n * @type {boolean}\n */\n get isInDST() {\n if (this.isOffsetFixed) {\n return false;\n } else {\n return (\n this.offset > this.set({ month: 1, day: 1 }).offset ||\n this.offset > this.set({ month: 5 }).offset\n );\n }\n }\n\n /**\n * Get those DateTimes which have the same local time as this DateTime, but a different offset from UTC\n * in this DateTime's zone. During DST changes local time can be ambiguous, for example\n * `2023-10-29T02:30:00` in `Europe/Berlin` can have offset `+01:00` or `+02:00`.\n * This method will return both possible DateTimes if this DateTime's local time is ambiguous.\n * @returns {DateTime[]}\n */\n getPossibleOffsets() {\n if (!this.isValid || this.isOffsetFixed) {\n return [this];\n }\n const dayMs = 86400000;\n const minuteMs = 60000;\n const localTS = objToLocalTS(this.c);\n const oEarlier = this.zone.offset(localTS - dayMs);\n const oLater = this.zone.offset(localTS + dayMs);\n\n const o1 = this.zone.offset(localTS - oEarlier * minuteMs);\n const o2 = this.zone.offset(localTS - oLater * minuteMs);\n if (o1 === o2) {\n return [this];\n }\n const ts1 = localTS - o1 * minuteMs;\n const ts2 = localTS - o2 * minuteMs;\n const c1 = tsToObj(ts1, o1);\n const c2 = tsToObj(ts2, o2);\n if (\n c1.hour === c2.hour &&\n c1.minute === c2.minute &&\n c1.second === c2.second &&\n c1.millisecond === c2.millisecond\n ) {\n return [clone(this, { ts: ts1 }), clone(this, { ts: ts2 })];\n }\n return [this];\n }\n\n /**\n * Returns true if this DateTime is in a leap year, false otherwise\n * @example DateTime.local(2016).isInLeapYear //=> true\n * @example DateTime.local(2013).isInLeapYear //=> false\n * @type {boolean}\n */\n get isInLeapYear() {\n return isLeapYear(this.year);\n }\n\n /**\n * Returns the number of days in this DateTime's month\n * @example DateTime.local(2016, 2).daysInMonth //=> 29\n * @example DateTime.local(2016, 3).daysInMonth //=> 31\n * @type {number}\n */\n get daysInMonth() {\n return daysInMonth(this.year, this.month);\n }\n\n /**\n * Returns the number of days in this DateTime's year\n * @example DateTime.local(2016).daysInYear //=> 366\n * @example DateTime.local(2013).daysInYear //=> 365\n * @type {number}\n */\n get daysInYear() {\n return this.isValid ? daysInYear(this.year) : NaN;\n }\n\n /**\n * Returns the number of weeks in this DateTime's year\n * @see https://en.wikipedia.org/wiki/ISO_week_date\n * @example DateTime.local(2004).weeksInWeekYear //=> 53\n * @example DateTime.local(2013).weeksInWeekYear //=> 52\n * @type {number}\n */\n get weeksInWeekYear() {\n return this.isValid ? weeksInWeekYear(this.weekYear) : NaN;\n }\n\n /**\n * Returns the number of weeks in this DateTime's local week year\n * @example DateTime.local(2020, 6, {locale: 'en-US'}).weeksInLocalWeekYear //=> 52\n * @example DateTime.local(2020, 6, {locale: 'de-DE'}).weeksInLocalWeekYear //=> 53\n * @type {number}\n */\n get weeksInLocalWeekYear() {\n return this.isValid\n ? weeksInWeekYear(\n this.localWeekYear,\n this.loc.getMinDaysInFirstWeek(),\n this.loc.getStartOfWeek()\n )\n : NaN;\n }\n\n /**\n * Returns the resolved Intl options for this DateTime.\n * This is useful in understanding the behavior of formatting methods\n * @param {Object} opts - the same options as toLocaleString\n * @return {Object}\n */\n resolvedLocaleOptions(opts = {}) {\n const { locale, numberingSystem, calendar } = Formatter.create(\n this.loc.clone(opts),\n opts\n ).resolvedOptions(this);\n return { locale, numberingSystem, outputCalendar: calendar };\n }\n\n // TRANSFORM\n\n /**\n * \"Set\" the DateTime's zone to UTC. Returns a newly-constructed DateTime.\n *\n * Equivalent to {@link DateTime#setZone}('utc')\n * @param {number} [offset=0] - optionally, an offset from UTC in minutes\n * @param {Object} [opts={}] - options to pass to `setZone()`\n * @return {DateTime}\n */\n toUTC(offset = 0, opts = {}) {\n return this.setZone(FixedOffsetZone.instance(offset), opts);\n }\n\n /**\n * \"Set\" the DateTime's zone to the host's local zone. Returns a newly-constructed DateTime.\n *\n * Equivalent to `setZone('local')`\n * @return {DateTime}\n */\n toLocal() {\n return this.setZone(Settings.defaultZone);\n }\n\n /**\n * \"Set\" the DateTime's zone to specified zone. Returns a newly-constructed DateTime.\n *\n * By default, the setter keeps the underlying time the same (as in, the same timestamp), but the new instance will report different local times and consider DSTs when making computations, as with {@link DateTime#plus}. You may wish to use {@link DateTime#toLocal} and {@link DateTime#toUTC} which provide simple convenience wrappers for commonly used zones.\n * @param {string|Zone} [zone='local'] - a zone identifier. As a string, that can be any IANA zone supported by the host environment, or a fixed-offset name of the form 'UTC+3', or the strings 'local' or 'utc'. You may also supply an instance of a {@link DateTime#Zone} class.\n * @param {Object} opts - options\n * @param {boolean} [opts.keepLocalTime=false] - If true, adjust the underlying time so that the local time stays the same, but in the target zone. You should rarely need this.\n * @return {DateTime}\n */\n setZone(zone, { keepLocalTime = false, keepCalendarTime = false } = {}) {\n zone = normalizeZone(zone, Settings.defaultZone);\n if (zone.equals(this.zone)) {\n return this;\n } else if (!zone.isValid) {\n return DateTime.invalid(unsupportedZone(zone));\n } else {\n let newTS = this.ts;\n if (keepLocalTime || keepCalendarTime) {\n const offsetGuess = zone.offset(this.ts);\n const asObj = this.toObject();\n [newTS] = objToTS(asObj, offsetGuess, zone);\n }\n return clone(this, { ts: newTS, zone });\n }\n }\n\n /**\n * \"Set\" the locale, numberingSystem, or outputCalendar. Returns a newly-constructed DateTime.\n * @param {Object} properties - the properties to set\n * @example DateTime.local(2017, 5, 25).reconfigure({ locale: 'en-GB' })\n * @return {DateTime}\n */\n reconfigure({ locale, numberingSystem, outputCalendar } = {}) {\n const loc = this.loc.clone({ locale, numberingSystem, outputCalendar });\n return clone(this, { loc });\n }\n\n /**\n * \"Set\" the locale. Returns a newly-constructed DateTime.\n * Just a convenient alias for reconfigure({ locale })\n * @example DateTime.local(2017, 5, 25).setLocale('en-GB')\n * @return {DateTime}\n */\n setLocale(locale) {\n return this.reconfigure({ locale });\n }\n\n /**\n * \"Set\" the values of specified units. Returns a newly-constructed DateTime.\n * You can only set units with this method; for \"setting\" metadata, see {@link DateTime#reconfigure} and {@link DateTime#setZone}.\n *\n * This method also supports setting locale-based week units, i.e. `localWeekday`, `localWeekNumber` and `localWeekYear`.\n * They cannot be mixed with ISO-week units like `weekday`.\n * @param {Object} values - a mapping of units to numbers\n * @example dt.set({ year: 2017 })\n * @example dt.set({ hour: 8, minute: 30 })\n * @example dt.set({ weekday: 5 })\n * @example dt.set({ year: 2005, ordinal: 234 })\n * @return {DateTime}\n */\n set(values) {\n if (!this.isValid) return this;\n\n const normalized = normalizeObject(values, normalizeUnitWithLocalWeeks);\n const { minDaysInFirstWeek, startOfWeek } = usesLocalWeekValues(normalized, this.loc);\n\n const settingWeekStuff =\n !isUndefined(normalized.weekYear) ||\n !isUndefined(normalized.weekNumber) ||\n !isUndefined(normalized.weekday),\n containsOrdinal = !isUndefined(normalized.ordinal),\n containsGregorYear = !isUndefined(normalized.year),\n containsGregorMD = !isUndefined(normalized.month) || !isUndefined(normalized.day),\n containsGregor = containsGregorYear || containsGregorMD,\n definiteWeekDef = normalized.weekYear || normalized.weekNumber;\n\n if ((containsGregor || containsOrdinal) && definiteWeekDef) {\n throw new ConflictingSpecificationError(\n \"Can't mix weekYear/weekNumber units with year/month/day or ordinals\"\n );\n }\n\n if (containsGregorMD && containsOrdinal) {\n throw new ConflictingSpecificationError(\"Can't mix ordinal dates with month/day\");\n }\n\n let mixed;\n if (settingWeekStuff) {\n mixed = weekToGregorian(\n { ...gregorianToWeek(this.c, minDaysInFirstWeek, startOfWeek), ...normalized },\n minDaysInFirstWeek,\n startOfWeek\n );\n } else if (!isUndefined(normalized.ordinal)) {\n mixed = ordinalToGregorian({ ...gregorianToOrdinal(this.c), ...normalized });\n } else {\n mixed = { ...this.toObject(), ...normalized };\n\n // if we didn't set the day but we ended up on an overflow date,\n // use the last day of the right month\n if (isUndefined(normalized.day)) {\n mixed.day = Math.min(daysInMonth(mixed.year, mixed.month), mixed.day);\n }\n }\n\n const [ts, o] = objToTS(mixed, this.o, this.zone);\n return clone(this, { ts, o });\n }\n\n /**\n * Add a period of time to this DateTime and return the resulting DateTime\n *\n * Adding hours, minutes, seconds, or milliseconds increases the timestamp by the right number of milliseconds. Adding days, months, or years shifts the calendar, accounting for DSTs and leap years along the way. Thus, `dt.plus({ hours: 24 })` may result in a different time than `dt.plus({ days: 1 })` if there's a DST shift in between.\n * @param {Duration|Object|number} duration - The amount to add. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()\n * @example DateTime.now().plus(123) //~> in 123 milliseconds\n * @example DateTime.now().plus({ minutes: 15 }) //~> in 15 minutes\n * @example DateTime.now().plus({ days: 1 }) //~> this time tomorrow\n * @example DateTime.now().plus({ days: -1 }) //~> this time yesterday\n * @example DateTime.now().plus({ hours: 3, minutes: 13 }) //~> in 3 hr, 13 min\n * @example DateTime.now().plus(Duration.fromObject({ hours: 3, minutes: 13 })) //~> in 3 hr, 13 min\n * @return {DateTime}\n */\n plus(duration) {\n if (!this.isValid) return this;\n const dur = Duration.fromDurationLike(duration);\n return clone(this, adjustTime(this, dur));\n }\n\n /**\n * Subtract a period of time to this DateTime and return the resulting DateTime\n * See {@link DateTime#plus}\n * @param {Duration|Object|number} duration - The amount to subtract. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()\n @return {DateTime}\n */\n minus(duration) {\n if (!this.isValid) return this;\n const dur = Duration.fromDurationLike(duration).negate();\n return clone(this, adjustTime(this, dur));\n }\n\n /**\n * \"Set\" this DateTime to the beginning of a unit of time.\n * @param {string} unit - The unit to go to the beginning of. Can be 'year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', or 'millisecond'.\n * @param {Object} opts - options\n * @param {boolean} [opts.useLocaleWeeks=false] - If true, use weeks based on the locale, i.e. use the locale-dependent start of the week\n * @example DateTime.local(2014, 3, 3).startOf('month').toISODate(); //=> '2014-03-01'\n * @example DateTime.local(2014, 3, 3).startOf('year').toISODate(); //=> '2014-01-01'\n * @example DateTime.local(2014, 3, 3).startOf('week').toISODate(); //=> '2014-03-03', weeks always start on Mondays\n * @example DateTime.local(2014, 3, 3, 5, 30).startOf('day').toISOTime(); //=> '00:00.000-05:00'\n * @example DateTime.local(2014, 3, 3, 5, 30).startOf('hour').toISOTime(); //=> '05:00:00.000-05:00'\n * @return {DateTime}\n */\n startOf(unit, { useLocaleWeeks = false } = {}) {\n if (!this.isValid) return this;\n\n const o = {},\n normalizedUnit = Duration.normalizeUnit(unit);\n switch (normalizedUnit) {\n case \"years\":\n o.month = 1;\n // falls through\n case \"quarters\":\n case \"months\":\n o.day = 1;\n // falls through\n case \"weeks\":\n case \"days\":\n o.hour = 0;\n // falls through\n case \"hours\":\n o.minute = 0;\n // falls through\n case \"minutes\":\n o.second = 0;\n // falls through\n case \"seconds\":\n o.millisecond = 0;\n break;\n case \"milliseconds\":\n break;\n // no default, invalid units throw in normalizeUnit()\n }\n\n if (normalizedUnit === \"weeks\") {\n if (useLocaleWeeks) {\n const startOfWeek = this.loc.getStartOfWeek();\n const { weekday } = this;\n if (weekday < startOfWeek) {\n o.weekNumber = this.weekNumber - 1;\n }\n o.weekday = startOfWeek;\n } else {\n o.weekday = 1;\n }\n }\n\n if (normalizedUnit === \"quarters\") {\n const q = Math.ceil(this.month / 3);\n o.month = (q - 1) * 3 + 1;\n }\n\n return this.set(o);\n }\n\n /**\n * \"Set\" this DateTime to the end (meaning the last millisecond) of a unit of time\n * @param {string} unit - The unit to go to the end of. Can be 'year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', or 'millisecond'.\n * @param {Object} opts - options\n * @param {boolean} [opts.useLocaleWeeks=false] - If true, use weeks based on the locale, i.e. use the locale-dependent start of the week\n * @example DateTime.local(2014, 3, 3).endOf('month').toISO(); //=> '2014-03-31T23:59:59.999-05:00'\n * @example DateTime.local(2014, 3, 3).endOf('year').toISO(); //=> '2014-12-31T23:59:59.999-05:00'\n * @example DateTime.local(2014, 3, 3).endOf('week').toISO(); // => '2014-03-09T23:59:59.999-05:00', weeks start on Mondays\n * @example DateTime.local(2014, 3, 3, 5, 30).endOf('day').toISO(); //=> '2014-03-03T23:59:59.999-05:00'\n * @example DateTime.local(2014, 3, 3, 5, 30).endOf('hour').toISO(); //=> '2014-03-03T05:59:59.999-05:00'\n * @return {DateTime}\n */\n endOf(unit, opts) {\n return this.isValid\n ? this.plus({ [unit]: 1 })\n .startOf(unit, opts)\n .minus(1)\n : this;\n }\n\n // OUTPUT\n\n /**\n * Returns a string representation of this DateTime formatted according to the specified format string.\n * **You may not want this.** See {@link DateTime#toLocaleString} for a more flexible formatting tool. For a table of tokens and their interpretations, see [here](https://moment.github.io/luxon/#/formatting?id=table-of-tokens).\n * Defaults to en-US if no locale has been specified, regardless of the system's locale.\n * @param {string} fmt - the format string\n * @param {Object} opts - opts to override the configuration options on this DateTime\n * @example DateTime.now().toFormat('yyyy LLL dd') //=> '2017 Apr 22'\n * @example DateTime.now().setLocale('fr').toFormat('yyyy LLL dd') //=> '2017 avr. 22'\n * @example DateTime.now().toFormat('yyyy LLL dd', { locale: \"fr\" }) //=> '2017 avr. 22'\n * @example DateTime.now().toFormat(\"HH 'hours and' mm 'minutes'\") //=> '20 hours and 55 minutes'\n * @return {string}\n */\n toFormat(fmt, opts = {}) {\n return this.isValid\n ? Formatter.create(this.loc.redefaultToEN(opts)).formatDateTimeFromString(this, fmt)\n : INVALID;\n }\n\n /**\n * Returns a localized string representing this date. Accepts the same options as the Intl.DateTimeFormat constructor and any presets defined by Luxon, such as `DateTime.DATE_FULL` or `DateTime.TIME_SIMPLE`.\n * The exact behavior of this method is browser-specific, but in general it will return an appropriate representation\n * of the DateTime in the assigned locale.\n * Defaults to the system's locale if no locale has been specified\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat\n * @param formatOpts {Object} - Intl.DateTimeFormat constructor options and configuration options\n * @param {Object} opts - opts to override the configuration options on this DateTime\n * @example DateTime.now().toLocaleString(); //=> 4/20/2017\n * @example DateTime.now().setLocale('en-gb').toLocaleString(); //=> '20/04/2017'\n * @example DateTime.now().toLocaleString(DateTime.DATE_FULL); //=> 'April 20, 2017'\n * @example DateTime.now().toLocaleString(DateTime.DATE_FULL, { locale: 'fr' }); //=> '28 ao\u00FBt 2022'\n * @example DateTime.now().toLocaleString(DateTime.TIME_SIMPLE); //=> '11:32 AM'\n * @example DateTime.now().toLocaleString(DateTime.DATETIME_SHORT); //=> '4/20/2017, 11:32 AM'\n * @example DateTime.now().toLocaleString({ weekday: 'long', month: 'long', day: '2-digit' }); //=> 'Thursday, April 20'\n * @example DateTime.now().toLocaleString({ weekday: 'short', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit' }); //=> 'Thu, Apr 20, 11:27 AM'\n * @example DateTime.now().toLocaleString({ hour: '2-digit', minute: '2-digit', hourCycle: 'h23' }); //=> '11:32'\n * @return {string}\n */\n toLocaleString(formatOpts = Formats.DATE_SHORT, opts = {}) {\n return this.isValid\n ? Formatter.create(this.loc.clone(opts), formatOpts).formatDateTime(this)\n : INVALID;\n }\n\n /**\n * Returns an array of format \"parts\", meaning individual tokens along with metadata. This is allows callers to post-process individual sections of the formatted output.\n * Defaults to the system's locale if no locale has been specified\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat/formatToParts\n * @param opts {Object} - Intl.DateTimeFormat constructor options, same as `toLocaleString`.\n * @example DateTime.now().toLocaleParts(); //=> [\n * //=> { type: 'day', value: '25' },\n * //=> { type: 'literal', value: '/' },\n * //=> { type: 'month', value: '05' },\n * //=> { type: 'literal', value: '/' },\n * //=> { type: 'year', value: '1982' }\n * //=> ]\n */\n toLocaleParts(opts = {}) {\n return this.isValid\n ? Formatter.create(this.loc.clone(opts), opts).formatDateTimeParts(this)\n : [];\n }\n\n /**\n * Returns an ISO 8601-compliant string representation of this DateTime\n * @param {Object} opts - options\n * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0\n * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0\n * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'\n * @param {boolean} [opts.extendedZone=false] - add the time zone format extension\n * @param {string} [opts.format='extended'] - choose between the basic and extended format\n * @example DateTime.utc(1983, 5, 25).toISO() //=> '1982-05-25T00:00:00.000Z'\n * @example DateTime.now().toISO() //=> '2017-04-22T20:47:05.335-04:00'\n * @example DateTime.now().toISO({ includeOffset: false }) //=> '2017-04-22T20:47:05.335'\n * @example DateTime.now().toISO({ format: 'basic' }) //=> '20170422T204705.335-0400'\n * @return {string}\n */\n toISO({\n format = \"extended\",\n suppressSeconds = false,\n suppressMilliseconds = false,\n includeOffset = true,\n extendedZone = false,\n } = {}) {\n if (!this.isValid) {\n return null;\n }\n\n const ext = format === \"extended\";\n\n let c = toISODate(this, ext);\n c += \"T\";\n c += toISOTime(this, ext, suppressSeconds, suppressMilliseconds, includeOffset, extendedZone);\n return c;\n }\n\n /**\n * Returns an ISO 8601-compliant string representation of this DateTime's date component\n * @param {Object} opts - options\n * @param {string} [opts.format='extended'] - choose between the basic and extended format\n * @example DateTime.utc(1982, 5, 25).toISODate() //=> '1982-05-25'\n * @example DateTime.utc(1982, 5, 25).toISODate({ format: 'basic' }) //=> '19820525'\n * @return {string}\n */\n toISODate({ format = \"extended\" } = {}) {\n if (!this.isValid) {\n return null;\n }\n\n return toISODate(this, format === \"extended\");\n }\n\n /**\n * Returns an ISO 8601-compliant string representation of this DateTime's week date\n * @example DateTime.utc(1982, 5, 25).toISOWeekDate() //=> '1982-W21-2'\n * @return {string}\n */\n toISOWeekDate() {\n return toTechFormat(this, \"kkkk-'W'WW-c\");\n }\n\n /**\n * Returns an ISO 8601-compliant string representation of this DateTime's time component\n * @param {Object} opts - options\n * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0\n * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0\n * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'\n * @param {boolean} [opts.extendedZone=true] - add the time zone format extension\n * @param {boolean} [opts.includePrefix=false] - include the `T` prefix\n * @param {string} [opts.format='extended'] - choose between the basic and extended format\n * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime() //=> '07:34:19.361Z'\n * @example DateTime.utc().set({ hour: 7, minute: 34, seconds: 0, milliseconds: 0 }).toISOTime({ suppressSeconds: true }) //=> '07:34Z'\n * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime({ format: 'basic' }) //=> '073419.361Z'\n * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime({ includePrefix: true }) //=> 'T07:34:19.361Z'\n * @return {string}\n */\n toISOTime({\n suppressMilliseconds = false,\n suppressSeconds = false,\n includeOffset = true,\n includePrefix = false,\n extendedZone = false,\n format = \"extended\",\n } = {}) {\n if (!this.isValid) {\n return null;\n }\n\n let c = includePrefix ? \"T\" : \"\";\n return (\n c +\n toISOTime(\n this,\n format === \"extended\",\n suppressSeconds,\n suppressMilliseconds,\n includeOffset,\n extendedZone\n )\n );\n }\n\n /**\n * Returns an RFC 2822-compatible string representation of this DateTime\n * @example DateTime.utc(2014, 7, 13).toRFC2822() //=> 'Sun, 13 Jul 2014 00:00:00 +0000'\n * @example DateTime.local(2014, 7, 13).toRFC2822() //=> 'Sun, 13 Jul 2014 00:00:00 -0400'\n * @return {string}\n */\n toRFC2822() {\n return toTechFormat(this, \"EEE, dd LLL yyyy HH:mm:ss ZZZ\", false);\n }\n\n /**\n * Returns a string representation of this DateTime appropriate for use in HTTP headers. The output is always expressed in GMT.\n * Specifically, the string conforms to RFC 1123.\n * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1\n * @example DateTime.utc(2014, 7, 13).toHTTP() //=> 'Sun, 13 Jul 2014 00:00:00 GMT'\n * @example DateTime.utc(2014, 7, 13, 19).toHTTP() //=> 'Sun, 13 Jul 2014 19:00:00 GMT'\n * @return {string}\n */\n toHTTP() {\n return toTechFormat(this.toUTC(), \"EEE, dd LLL yyyy HH:mm:ss 'GMT'\");\n }\n\n /**\n * Returns a string representation of this DateTime appropriate for use in SQL Date\n * @example DateTime.utc(2014, 7, 13).toSQLDate() //=> '2014-07-13'\n * @return {string}\n */\n toSQLDate() {\n if (!this.isValid) {\n return null;\n }\n return toISODate(this, true);\n }\n\n /**\n * Returns a string representation of this DateTime appropriate for use in SQL Time\n * @param {Object} opts - options\n * @param {boolean} [opts.includeZone=false] - include the zone, such as 'America/New_York'. Overrides includeOffset.\n * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'\n * @param {boolean} [opts.includeOffsetSpace=true] - include the space between the time and the offset, such as '05:15:16.345 -04:00'\n * @example DateTime.utc().toSQL() //=> '05:15:16.345'\n * @example DateTime.now().toSQL() //=> '05:15:16.345 -04:00'\n * @example DateTime.now().toSQL({ includeOffset: false }) //=> '05:15:16.345'\n * @example DateTime.now().toSQL({ includeZone: false }) //=> '05:15:16.345 America/New_York'\n * @return {string}\n */\n toSQLTime({ includeOffset = true, includeZone = false, includeOffsetSpace = true } = {}) {\n let fmt = \"HH:mm:ss.SSS\";\n\n if (includeZone || includeOffset) {\n if (includeOffsetSpace) {\n fmt += \" \";\n }\n if (includeZone) {\n fmt += \"z\";\n } else if (includeOffset) {\n fmt += \"ZZ\";\n }\n }\n\n return toTechFormat(this, fmt, true);\n }\n\n /**\n * Returns a string representation of this DateTime appropriate for use in SQL DateTime\n * @param {Object} opts - options\n * @param {boolean} [opts.includeZone=false] - include the zone, such as 'America/New_York'. Overrides includeOffset.\n * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'\n * @param {boolean} [opts.includeOffsetSpace=true] - include the space between the time and the offset, such as '05:15:16.345 -04:00'\n * @example DateTime.utc(2014, 7, 13).toSQL() //=> '2014-07-13 00:00:00.000 Z'\n * @example DateTime.local(2014, 7, 13).toSQL() //=> '2014-07-13 00:00:00.000 -04:00'\n * @example DateTime.local(2014, 7, 13).toSQL({ includeOffset: false }) //=> '2014-07-13 00:00:00.000'\n * @example DateTime.local(2014, 7, 13).toSQL({ includeZone: true }) //=> '2014-07-13 00:00:00.000 America/New_York'\n * @return {string}\n */\n toSQL(opts = {}) {\n if (!this.isValid) {\n return null;\n }\n\n return `${this.toSQLDate()} ${this.toSQLTime(opts)}`;\n }\n\n /**\n * Returns a string representation of this DateTime appropriate for debugging\n * @return {string}\n */\n toString() {\n return this.isValid ? this.toISO() : INVALID;\n }\n\n /**\n * Returns a string representation of this DateTime appropriate for the REPL.\n * @return {string}\n */\n [Symbol.for(\"nodejs.util.inspect.custom\")]() {\n if (this.isValid) {\n return `DateTime { ts: ${this.toISO()}, zone: ${this.zone.name}, locale: ${this.locale} }`;\n } else {\n return `DateTime { Invalid, reason: ${this.invalidReason} }`;\n }\n }\n\n /**\n * Returns the epoch milliseconds of this DateTime. Alias of {@link DateTime#toMillis}\n * @return {number}\n */\n valueOf() {\n return this.toMillis();\n }\n\n /**\n * Returns the epoch milliseconds of this DateTime.\n * @return {number}\n */\n toMillis() {\n return this.isValid ? this.ts : NaN;\n }\n\n /**\n * Returns the epoch seconds of this DateTime.\n * @return {number}\n */\n toSeconds() {\n return this.isValid ? this.ts / 1000 : NaN;\n }\n\n /**\n * Returns the epoch seconds (as a whole number) of this DateTime.\n * @return {number}\n */\n toUnixInteger() {\n return this.isValid ? Math.floor(this.ts / 1000) : NaN;\n }\n\n /**\n * Returns an ISO 8601 representation of this DateTime appropriate for use in JSON.\n * @return {string}\n */\n toJSON() {\n return this.toISO();\n }\n\n /**\n * Returns a BSON serializable equivalent to this DateTime.\n * @return {Date}\n */\n toBSON() {\n return this.toJSDate();\n }\n\n /**\n * Returns a JavaScript object with this DateTime's year, month, day, and so on.\n * @param opts - options for generating the object\n * @param {boolean} [opts.includeConfig=false] - include configuration attributes in the output\n * @example DateTime.now().toObject() //=> { year: 2017, month: 4, day: 22, hour: 20, minute: 49, second: 42, millisecond: 268 }\n * @return {Object}\n */\n toObject(opts = {}) {\n if (!this.isValid) return {};\n\n const base = { ...this.c };\n\n if (opts.includeConfig) {\n base.outputCalendar = this.outputCalendar;\n base.numberingSystem = this.loc.numberingSystem;\n base.locale = this.loc.locale;\n }\n return base;\n }\n\n /**\n * Returns a JavaScript Date equivalent to this DateTime.\n * @return {Date}\n */\n toJSDate() {\n return new Date(this.isValid ? this.ts : NaN);\n }\n\n // COMPARE\n\n /**\n * Return the difference between two DateTimes as a Duration.\n * @param {DateTime} otherDateTime - the DateTime to compare this one to\n * @param {string|string[]} [unit=['milliseconds']] - the unit or array of units (such as 'hours' or 'days') to include in the duration.\n * @param {Object} opts - options that affect the creation of the Duration\n * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use\n * @example\n * var i1 = DateTime.fromISO('1982-05-25T09:45'),\n * i2 = DateTime.fromISO('1983-10-14T10:30');\n * i2.diff(i1).toObject() //=> { milliseconds: 43807500000 }\n * i2.diff(i1, 'hours').toObject() //=> { hours: 12168.75 }\n * i2.diff(i1, ['months', 'days']).toObject() //=> { months: 16, days: 19.03125 }\n * i2.diff(i1, ['months', 'days', 'hours']).toObject() //=> { months: 16, days: 19, hours: 0.75 }\n * @return {Duration}\n */\n diff(otherDateTime, unit = \"milliseconds\", opts = {}) {\n if (!this.isValid || !otherDateTime.isValid) {\n return Duration.invalid(\"created by diffing an invalid DateTime\");\n }\n\n const durOpts = { locale: this.locale, numberingSystem: this.numberingSystem, ...opts };\n\n const units = maybeArray(unit).map(Duration.normalizeUnit),\n otherIsLater = otherDateTime.valueOf() > this.valueOf(),\n earlier = otherIsLater ? this : otherDateTime,\n later = otherIsLater ? otherDateTime : this,\n diffed = diff(earlier, later, units, durOpts);\n\n return otherIsLater ? diffed.negate() : diffed;\n }\n\n /**\n * Return the difference between this DateTime and right now.\n * See {@link DateTime#diff}\n * @param {string|string[]} [unit=['milliseconds']] - the unit or units units (such as 'hours' or 'days') to include in the duration\n * @param {Object} opts - options that affect the creation of the Duration\n * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use\n * @return {Duration}\n */\n diffNow(unit = \"milliseconds\", opts = {}) {\n return this.diff(DateTime.now(), unit, opts);\n }\n\n /**\n * Return an Interval spanning between this DateTime and another DateTime\n * @param {DateTime} otherDateTime - the other end point of the Interval\n * @return {Interval}\n */\n until(otherDateTime) {\n return this.isValid ? Interval.fromDateTimes(this, otherDateTime) : this;\n }\n\n /**\n * Return whether this DateTime is in the same unit of time as another DateTime.\n * Higher-order units must also be identical for this function to return `true`.\n * Note that time zones are **ignored** in this comparison, which compares the **local** calendar time. Use {@link DateTime#setZone} to convert one of the dates if needed.\n * @param {DateTime} otherDateTime - the other DateTime\n * @param {string} unit - the unit of time to check sameness on\n * @param {Object} opts - options\n * @param {boolean} [opts.useLocaleWeeks=false] - If true, use weeks based on the locale, i.e. use the locale-dependent start of the week; only the locale of this DateTime is used\n * @example DateTime.now().hasSame(otherDT, 'day'); //~> true if otherDT is in the same current calendar day\n * @return {boolean}\n */\n hasSame(otherDateTime, unit, opts) {\n if (!this.isValid) return false;\n\n const inputMs = otherDateTime.valueOf();\n const adjustedToZone = this.setZone(otherDateTime.zone, { keepLocalTime: true });\n return (\n adjustedToZone.startOf(unit, opts) <= inputMs && inputMs <= adjustedToZone.endOf(unit, opts)\n );\n }\n\n /**\n * Equality check\n * Two DateTimes are equal if and only if they represent the same millisecond, have the same zone and location, and are both valid.\n * To compare just the millisecond values, use `+dt1 === +dt2`.\n * @param {DateTime} other - the other DateTime\n * @return {boolean}\n */\n equals(other) {\n return (\n this.isValid &&\n other.isValid &&\n this.valueOf() === other.valueOf() &&\n this.zone.equals(other.zone) &&\n this.loc.equals(other.loc)\n );\n }\n\n /**\n * Returns a string representation of a this time relative to now, such as \"in two days\". Can only internationalize if your\n * platform supports Intl.RelativeTimeFormat. Rounds down by default.\n * @param {Object} options - options that affect the output\n * @param {DateTime} [options.base=DateTime.now()] - the DateTime to use as the basis to which this time is compared. Defaults to now.\n * @param {string} [options.style=\"long\"] - the style of units, must be \"long\", \"short\", or \"narrow\"\n * @param {string|string[]} options.unit - use a specific unit or array of units; if omitted, or an array, the method will pick the best unit. Use an array or one of \"years\", \"quarters\", \"months\", \"weeks\", \"days\", \"hours\", \"minutes\", or \"seconds\"\n * @param {boolean} [options.round=true] - whether to round the numbers in the output.\n * @param {number} [options.padding=0] - padding in milliseconds. This allows you to round up the result if it fits inside the threshold. Don't use in combination with {round: false} because the decimal output will include the padding.\n * @param {string} options.locale - override the locale of this DateTime\n * @param {string} options.numberingSystem - override the numberingSystem of this DateTime. The Intl system may choose not to honor this\n * @example DateTime.now().plus({ days: 1 }).toRelative() //=> \"in 1 day\"\n * @example DateTime.now().setLocale(\"es\").toRelative({ days: 1 }) //=> \"dentro de 1 d\u00EDa\"\n * @example DateTime.now().plus({ days: 1 }).toRelative({ locale: \"fr\" }) //=> \"dans 23 heures\"\n * @example DateTime.now().minus({ days: 2 }).toRelative() //=> \"2 days ago\"\n * @example DateTime.now().minus({ days: 2 }).toRelative({ unit: \"hours\" }) //=> \"48 hours ago\"\n * @example DateTime.now().minus({ hours: 36 }).toRelative({ round: false }) //=> \"1.5 days ago\"\n */\n toRelative(options = {}) {\n if (!this.isValid) return null;\n const base = options.base || DateTime.fromObject({}, { zone: this.zone }),\n padding = options.padding ? (this < base ? -options.padding : options.padding) : 0;\n let units = [\"years\", \"months\", \"days\", \"hours\", \"minutes\", \"seconds\"];\n let unit = options.unit;\n if (Array.isArray(options.unit)) {\n units = options.unit;\n unit = undefined;\n }\n return diffRelative(base, this.plus(padding), {\n ...options,\n numeric: \"always\",\n units,\n unit,\n });\n }\n\n /**\n * Returns a string representation of this date relative to today, such as \"yesterday\" or \"next month\".\n * Only internationalizes on platforms that supports Intl.RelativeTimeFormat.\n * @param {Object} options - options that affect the output\n * @param {DateTime} [options.base=DateTime.now()] - the DateTime to use as the basis to which this time is compared. Defaults to now.\n * @param {string} options.locale - override the locale of this DateTime\n * @param {string} options.unit - use a specific unit; if omitted, the method will pick the unit. Use one of \"years\", \"quarters\", \"months\", \"weeks\", or \"days\"\n * @param {string} options.numberingSystem - override the numberingSystem of this DateTime. The Intl system may choose not to honor this\n * @example DateTime.now().plus({ days: 1 }).toRelativeCalendar() //=> \"tomorrow\"\n * @example DateTime.now().setLocale(\"es\").plus({ days: 1 }).toRelative() //=> \"\"ma\u00F1ana\"\n * @example DateTime.now().plus({ days: 1 }).toRelativeCalendar({ locale: \"fr\" }) //=> \"demain\"\n * @example DateTime.now().minus({ days: 2 }).toRelativeCalendar() //=> \"2 days ago\"\n */\n toRelativeCalendar(options = {}) {\n if (!this.isValid) return null;\n\n return diffRelative(options.base || DateTime.fromObject({}, { zone: this.zone }), this, {\n ...options,\n numeric: \"auto\",\n units: [\"years\", \"months\", \"days\"],\n calendary: true,\n });\n }\n\n /**\n * Return the min of several date times\n * @param {...DateTime} dateTimes - the DateTimes from which to choose the minimum\n * @return {DateTime} the min DateTime, or undefined if called with no argument\n */\n static min(...dateTimes) {\n if (!dateTimes.every(DateTime.isDateTime)) {\n throw new InvalidArgumentError(\"min requires all arguments be DateTimes\");\n }\n return bestBy(dateTimes, (i) => i.valueOf(), Math.min);\n }\n\n /**\n * Return the max of several date times\n * @param {...DateTime} dateTimes - the DateTimes from which to choose the maximum\n * @return {DateTime} the max DateTime, or undefined if called with no argument\n */\n static max(...dateTimes) {\n if (!dateTimes.every(DateTime.isDateTime)) {\n throw new InvalidArgumentError(\"max requires all arguments be DateTimes\");\n }\n return bestBy(dateTimes, (i) => i.valueOf(), Math.max);\n }\n\n // MISC\n\n /**\n * Explain how a string would be parsed by fromFormat()\n * @param {string} text - the string to parse\n * @param {string} fmt - the format the string is expected to be in (see description)\n * @param {Object} options - options taken by fromFormat()\n * @return {Object}\n */\n static fromFormatExplain(text, fmt, options = {}) {\n const { locale = null, numberingSystem = null } = options,\n localeToUse = Locale.fromOpts({\n locale,\n numberingSystem,\n defaultToEN: true,\n });\n return explainFromTokens(localeToUse, text, fmt);\n }\n\n /**\n * @deprecated use fromFormatExplain instead\n */\n static fromStringExplain(text, fmt, options = {}) {\n return DateTime.fromFormatExplain(text, fmt, options);\n }\n\n /**\n * Build a parser for `fmt` using the given locale. This parser can be passed\n * to {@link DateTime.fromFormatParser} to a parse a date in this format. This\n * can be used to optimize cases where many dates need to be parsed in a\n * specific format.\n *\n * @param {String} fmt - the format the string is expected to be in (see\n * description)\n * @param {Object} options - options used to set locale and numberingSystem\n * for parser\n * @returns {TokenParser} - opaque object to be used\n */\n static buildFormatParser(fmt, options = {}) {\n const { locale = null, numberingSystem = null } = options,\n localeToUse = Locale.fromOpts({\n locale,\n numberingSystem,\n defaultToEN: true,\n });\n return new TokenParser(localeToUse, fmt);\n }\n\n /**\n * Create a DateTime from an input string and format parser.\n *\n * The format parser must have been created with the same locale as this call.\n *\n * @param {String} text - the string to parse\n * @param {TokenParser} formatParser - parser from {@link DateTime.buildFormatParser}\n * @param {Object} opts - options taken by fromFormat()\n * @returns {DateTime}\n */\n static fromFormatParser(text, formatParser, opts = {}) {\n if (isUndefined(text) || isUndefined(formatParser)) {\n throw new InvalidArgumentError(\n \"fromFormatParser requires an input string and a format parser\"\n );\n }\n const { locale = null, numberingSystem = null } = opts,\n localeToUse = Locale.fromOpts({\n locale,\n numberingSystem,\n defaultToEN: true,\n });\n\n if (!localeToUse.equals(formatParser.locale)) {\n throw new InvalidArgumentError(\n `fromFormatParser called with a locale of ${localeToUse}, ` +\n `but the format parser was created for ${formatParser.locale}`\n );\n }\n\n const { result, zone, specificOffset, invalidReason } = formatParser.explainFromTokens(text);\n\n if (invalidReason) {\n return DateTime.invalid(invalidReason);\n } else {\n return parseDataToDateTime(\n result,\n zone,\n opts,\n `format ${formatParser.format}`,\n text,\n specificOffset\n );\n }\n }\n\n // FORMAT PRESETS\n\n /**\n * {@link DateTime#toLocaleString} format like 10/14/1983\n * @type {Object}\n */\n static get DATE_SHORT() {\n return Formats.DATE_SHORT;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like 'Oct 14, 1983'\n * @type {Object}\n */\n static get DATE_MED() {\n return Formats.DATE_MED;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like 'Fri, Oct 14, 1983'\n * @type {Object}\n */\n static get DATE_MED_WITH_WEEKDAY() {\n return Formats.DATE_MED_WITH_WEEKDAY;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like 'October 14, 1983'\n * @type {Object}\n */\n static get DATE_FULL() {\n return Formats.DATE_FULL;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like 'Tuesday, October 14, 1983'\n * @type {Object}\n */\n static get DATE_HUGE() {\n return Formats.DATE_HUGE;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like '09:30 AM'. Only 12-hour if the locale is.\n * @type {Object}\n */\n static get TIME_SIMPLE() {\n return Formats.TIME_SIMPLE;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like '09:30:23 AM'. Only 12-hour if the locale is.\n * @type {Object}\n */\n static get TIME_WITH_SECONDS() {\n return Formats.TIME_WITH_SECONDS;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like '09:30:23 AM EDT'. Only 12-hour if the locale is.\n * @type {Object}\n */\n static get TIME_WITH_SHORT_OFFSET() {\n return Formats.TIME_WITH_SHORT_OFFSET;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like '09:30:23 AM Eastern Daylight Time'. Only 12-hour if the locale is.\n * @type {Object}\n */\n static get TIME_WITH_LONG_OFFSET() {\n return Formats.TIME_WITH_LONG_OFFSET;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like '09:30', always 24-hour.\n * @type {Object}\n */\n static get TIME_24_SIMPLE() {\n return Formats.TIME_24_SIMPLE;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like '09:30:23', always 24-hour.\n * @type {Object}\n */\n static get TIME_24_WITH_SECONDS() {\n return Formats.TIME_24_WITH_SECONDS;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like '09:30:23 EDT', always 24-hour.\n * @type {Object}\n */\n static get TIME_24_WITH_SHORT_OFFSET() {\n return Formats.TIME_24_WITH_SHORT_OFFSET;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like '09:30:23 Eastern Daylight Time', always 24-hour.\n * @type {Object}\n */\n static get TIME_24_WITH_LONG_OFFSET() {\n return Formats.TIME_24_WITH_LONG_OFFSET;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like '10/14/1983, 9:30 AM'. Only 12-hour if the locale is.\n * @type {Object}\n */\n static get DATETIME_SHORT() {\n return Formats.DATETIME_SHORT;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like '10/14/1983, 9:30:33 AM'. Only 12-hour if the locale is.\n * @type {Object}\n */\n static get DATETIME_SHORT_WITH_SECONDS() {\n return Formats.DATETIME_SHORT_WITH_SECONDS;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like 'Oct 14, 1983, 9:30 AM'. Only 12-hour if the locale is.\n * @type {Object}\n */\n static get DATETIME_MED() {\n return Formats.DATETIME_MED;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like 'Oct 14, 1983, 9:30:33 AM'. Only 12-hour if the locale is.\n * @type {Object}\n */\n static get DATETIME_MED_WITH_SECONDS() {\n return Formats.DATETIME_MED_WITH_SECONDS;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like 'Fri, 14 Oct 1983, 9:30 AM'. Only 12-hour if the locale is.\n * @type {Object}\n */\n static get DATETIME_MED_WITH_WEEKDAY() {\n return Formats.DATETIME_MED_WITH_WEEKDAY;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like 'October 14, 1983, 9:30 AM EDT'. Only 12-hour if the locale is.\n * @type {Object}\n */\n static get DATETIME_FULL() {\n return Formats.DATETIME_FULL;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like 'October 14, 1983, 9:30:33 AM EDT'. Only 12-hour if the locale is.\n * @type {Object}\n */\n static get DATETIME_FULL_WITH_SECONDS() {\n return Formats.DATETIME_FULL_WITH_SECONDS;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like 'Friday, October 14, 1983, 9:30 AM Eastern Daylight Time'. Only 12-hour if the locale is.\n * @type {Object}\n */\n static get DATETIME_HUGE() {\n return Formats.DATETIME_HUGE;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like 'Friday, October 14, 1983, 9:30:33 AM Eastern Daylight Time'. Only 12-hour if the locale is.\n * @type {Object}\n */\n static get DATETIME_HUGE_WITH_SECONDS() {\n return Formats.DATETIME_HUGE_WITH_SECONDS;\n }\n}\n\n/**\n * @private\n */\nexport function friendlyDateTime(dateTimeish) {\n if (DateTime.isDateTime(dateTimeish)) {\n return dateTimeish;\n } else if (dateTimeish && dateTimeish.valueOf && isNumber(dateTimeish.valueOf())) {\n return DateTime.fromJSDate(dateTimeish);\n } else if (dateTimeish && typeof dateTimeish === \"object\") {\n return DateTime.fromObject(dateTimeish);\n } else {\n throw new InvalidArgumentError(\n `Unknown datetime argument: ${dateTimeish}, of type ${typeof dateTimeish}`\n );\n }\n}\n", "import DateTime from \"./datetime.js\";\nimport Duration from \"./duration.js\";\nimport Interval from \"./interval.js\";\nimport Info from \"./info.js\";\nimport Zone from \"./zone.js\";\nimport FixedOffsetZone from \"./zones/fixedOffsetZone.js\";\nimport IANAZone from \"./zones/IANAZone.js\";\nimport InvalidZone from \"./zones/invalidZone.js\";\nimport SystemZone from \"./zones/systemZone.js\";\nimport Settings from \"./settings.js\";\n\nconst VERSION = \"3.5.0\";\n\nexport {\n VERSION,\n DateTime,\n Duration,\n Interval,\n Info,\n Zone,\n FixedOffsetZone,\n IANAZone,\n InvalidZone,\n SystemZone,\n Settings,\n};\n", "function _typeof(o) {\n \"@babel/helpers - typeof\";\n\n return _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 }, _typeof(o);\n}\nexport { _typeof as default };", "import _typeof from \"./typeof.js\";\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}\nexport { toPrimitive as default };", "import _typeof from \"./typeof.js\";\nimport toPrimitive from \"./toPrimitive.js\";\nfunction toPropertyKey(t) {\n var i = toPrimitive(t, \"string\");\n return \"symbol\" == _typeof(i) ? i : i + \"\";\n}\nexport { toPropertyKey as default };", "import toPropertyKey from \"./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}\nexport { _defineProperty as default };", "import defineProperty from \"./defineProperty.js\";\nfunction ownKeys(e, r) {\n var t = Object.keys(e);\n if (Object.getOwnPropertySymbols) {\n var o = Object.getOwnPropertySymbols(e);\n r && (o = o.filter(function (r) {\n return Object.getOwnPropertyDescriptor(e, r).enumerable;\n })), t.push.apply(t, o);\n }\n return t;\n}\nfunction _objectSpread2(e) {\n for (var r = 1; r < arguments.length; r++) {\n var t = null != arguments[r] ? arguments[r] : {};\n r % 2 ? ownKeys(Object(t), !0).forEach(function (r) {\n defineProperty(e, r, t[r]);\n }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) {\n Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));\n });\n }\n return e;\n}\nexport { _objectSpread2 as default };", "import _objectSpread from '@babel/runtime/helpers/esm/objectSpread2';\n\n/**\n * Adapted from React: https://github.com/facebook/react/blob/master/packages/shared/formatProdErrorMessage.js\n *\n * Do not require this module directly! Use normal throw error calls. These messages will be replaced with error codes\n * during build.\n * @param {number} code\n */\nfunction formatProdErrorMessage(code) {\n return \"Minified Redux error #\" + code + \"; visit https://redux.js.org/Errors?code=\" + code + \" for the full message or \" + 'use the non-minified dev environment for full errors. ';\n}\n\n// Inlined version of the `symbol-observable` polyfill\nvar $$observable = (function () {\n return typeof Symbol === 'function' && Symbol.observable || '@@observable';\n})();\n\n/**\n * These are private action types reserved by Redux.\n * For any unknown actions, you must return the current state.\n * If the current state is undefined, you must return the initial state.\n * Do not reference these action types directly in your code.\n */\nvar randomString = function randomString() {\n return Math.random().toString(36).substring(7).split('').join('.');\n};\n\nvar ActionTypes = {\n INIT: \"@@redux/INIT\" + randomString(),\n REPLACE: \"@@redux/REPLACE\" + randomString(),\n PROBE_UNKNOWN_ACTION: function PROBE_UNKNOWN_ACTION() {\n return \"@@redux/PROBE_UNKNOWN_ACTION\" + randomString();\n }\n};\n\n/**\n * @param {any} obj The object to inspect.\n * @returns {boolean} True if the argument appears to be a plain object.\n */\nfunction isPlainObject(obj) {\n if (typeof obj !== 'object' || obj === null) return false;\n var proto = obj;\n\n while (Object.getPrototypeOf(proto) !== null) {\n proto = Object.getPrototypeOf(proto);\n }\n\n return Object.getPrototypeOf(obj) === proto;\n}\n\n// Inlined / shortened version of `kindOf` from https://github.com/jonschlinkert/kind-of\nfunction miniKindOf(val) {\n if (val === void 0) return 'undefined';\n if (val === null) return 'null';\n var type = typeof val;\n\n switch (type) {\n case 'boolean':\n case 'string':\n case 'number':\n case 'symbol':\n case 'function':\n {\n return type;\n }\n }\n\n if (Array.isArray(val)) return 'array';\n if (isDate(val)) return 'date';\n if (isError(val)) return 'error';\n var constructorName = ctorName(val);\n\n switch (constructorName) {\n case 'Symbol':\n case 'Promise':\n case 'WeakMap':\n case 'WeakSet':\n case 'Map':\n case 'Set':\n return constructorName;\n } // other\n\n\n return type.slice(8, -1).toLowerCase().replace(/\\s/g, '');\n}\n\nfunction ctorName(val) {\n return typeof val.constructor === 'function' ? val.constructor.name : null;\n}\n\nfunction isError(val) {\n return val instanceof Error || typeof val.message === 'string' && val.constructor && typeof val.constructor.stackTraceLimit === 'number';\n}\n\nfunction isDate(val) {\n if (val instanceof Date) return true;\n return typeof val.toDateString === 'function' && typeof val.getDate === 'function' && typeof val.setDate === 'function';\n}\n\nfunction kindOf(val) {\n var typeOfVal = typeof val;\n\n if (process.env.NODE_ENV !== 'production') {\n typeOfVal = miniKindOf(val);\n }\n\n return typeOfVal;\n}\n\n/**\n * @deprecated\n *\n * **We recommend using the `configureStore` method\n * of the `@reduxjs/toolkit` package**, which replaces `createStore`.\n *\n * Redux Toolkit is our recommended approach for writing Redux logic today,\n * including store setup, reducers, data fetching, and more.\n *\n * **For more details, please read this Redux docs page:**\n * **https://redux.js.org/introduction/why-rtk-is-redux-today**\n *\n * `configureStore` from Redux Toolkit is an improved version of `createStore` that\n * simplifies setup and helps avoid common bugs.\n *\n * You should not be using the `redux` core package by itself today, except for learning purposes.\n * The `createStore` method from the core `redux` package will not be removed, but we encourage\n * all users to migrate to using Redux Toolkit for all Redux code.\n *\n * If you want to use `createStore` without this visual deprecation warning, use\n * the `legacy_createStore` import instead:\n *\n * `import { legacy_createStore as createStore} from 'redux'`\n *\n */\n\nfunction createStore(reducer, preloadedState, enhancer) {\n var _ref2;\n\n if (typeof preloadedState === 'function' && typeof enhancer === 'function' || typeof enhancer === 'function' && typeof arguments[3] === 'function') {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(0) : 'It looks like you are passing several store enhancers to ' + 'createStore(). This is not supported. Instead, compose them ' + 'together to a single function. See https://redux.js.org/tutorials/fundamentals/part-4-store#creating-a-store-with-enhancers for an example.');\n }\n\n if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') {\n enhancer = preloadedState;\n preloadedState = undefined;\n }\n\n if (typeof enhancer !== 'undefined') {\n if (typeof enhancer !== 'function') {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(1) : \"Expected the enhancer to be a function. Instead, received: '\" + kindOf(enhancer) + \"'\");\n }\n\n return enhancer(createStore)(reducer, preloadedState);\n }\n\n if (typeof reducer !== 'function') {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(2) : \"Expected the root reducer to be a function. Instead, received: '\" + kindOf(reducer) + \"'\");\n }\n\n var currentReducer = reducer;\n var currentState = preloadedState;\n var currentListeners = [];\n var nextListeners = currentListeners;\n var isDispatching = false;\n /**\n * This makes a shallow copy of currentListeners so we can use\n * nextListeners as a temporary list while dispatching.\n *\n * This prevents any bugs around consumers calling\n * subscribe/unsubscribe in the middle of a dispatch.\n */\n\n function ensureCanMutateNextListeners() {\n if (nextListeners === currentListeners) {\n nextListeners = currentListeners.slice();\n }\n }\n /**\n * Reads the state tree managed by the store.\n *\n * @returns {any} The current state tree of your application.\n */\n\n\n function getState() {\n if (isDispatching) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(3) : 'You may not call store.getState() while the reducer is executing. ' + 'The reducer has already received the state as an argument. ' + 'Pass it down from the top reducer instead of reading it from the store.');\n }\n\n return currentState;\n }\n /**\n * Adds a change listener. It will be called any time an action is dispatched,\n * and some part of the state tree may potentially have changed. You may then\n * call `getState()` to read the current state tree inside the callback.\n *\n * You may call `dispatch()` from a change listener, with the following\n * caveats:\n *\n * 1. The subscriptions are snapshotted just before every `dispatch()` call.\n * If you subscribe or unsubscribe while the listeners are being invoked, this\n * will not have any effect on the `dispatch()` that is currently in progress.\n * However, the next `dispatch()` call, whether nested or not, will use a more\n * recent snapshot of the subscription list.\n *\n * 2. The listener should not expect to see all state changes, as the state\n * might have been updated multiple times during a nested `dispatch()` before\n * the listener is called. It is, however, guaranteed that all subscribers\n * registered before the `dispatch()` started will be called with the latest\n * state by the time it exits.\n *\n * @param {Function} listener A callback to be invoked on every dispatch.\n * @returns {Function} A function to remove this change listener.\n */\n\n\n function subscribe(listener) {\n if (typeof listener !== 'function') {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(4) : \"Expected the listener to be a function. Instead, received: '\" + kindOf(listener) + \"'\");\n }\n\n if (isDispatching) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(5) : 'You may not call store.subscribe() while the reducer is executing. ' + 'If you would like to be notified after the store has been updated, subscribe from a ' + 'component and invoke store.getState() in the callback to access the latest state. ' + 'See https://redux.js.org/api/store#subscribelistener for more details.');\n }\n\n var isSubscribed = true;\n ensureCanMutateNextListeners();\n nextListeners.push(listener);\n return function unsubscribe() {\n if (!isSubscribed) {\n return;\n }\n\n if (isDispatching) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(6) : 'You may not unsubscribe from a store listener while the reducer is executing. ' + 'See https://redux.js.org/api/store#subscribelistener for more details.');\n }\n\n isSubscribed = false;\n ensureCanMutateNextListeners();\n var index = nextListeners.indexOf(listener);\n nextListeners.splice(index, 1);\n currentListeners = null;\n };\n }\n /**\n * Dispatches an action. It is the only way to trigger a state change.\n *\n * The `reducer` function, used to create the store, will be called with the\n * current state tree and the given `action`. Its return value will\n * be considered the **next** state of the tree, and the change listeners\n * will be notified.\n *\n * The base implementation only supports plain object actions. If you want to\n * dispatch a Promise, an Observable, a thunk, or something else, you need to\n * wrap your store creating function into the corresponding middleware. For\n * example, see the documentation for the `redux-thunk` package. Even the\n * middleware will eventually dispatch plain object actions using this method.\n *\n * @param {Object} action A plain object representing \u201Cwhat changed\u201D. It is\n * a good idea to keep actions serializable so you can record and replay user\n * sessions, or use the time travelling `redux-devtools`. An action must have\n * a `type` property which may not be `undefined`. It is a good idea to use\n * string constants for action types.\n *\n * @returns {Object} For convenience, the same action object you dispatched.\n *\n * Note that, if you use a custom middleware, it may wrap `dispatch()` to\n * return something else (for example, a Promise you can await).\n */\n\n\n function dispatch(action) {\n if (!isPlainObject(action)) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(7) : \"Actions must be plain objects. Instead, the actual type was: '\" + kindOf(action) + \"'. You may need to add middleware to your store setup to handle dispatching other values, such as 'redux-thunk' to handle dispatching functions. See https://redux.js.org/tutorials/fundamentals/part-4-store#middleware and https://redux.js.org/tutorials/fundamentals/part-6-async-logic#using-the-redux-thunk-middleware for examples.\");\n }\n\n if (typeof action.type === 'undefined') {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(8) : 'Actions may not have an undefined \"type\" property. You may have misspelled an action type string constant.');\n }\n\n if (isDispatching) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(9) : 'Reducers may not dispatch actions.');\n }\n\n try {\n isDispatching = true;\n currentState = currentReducer(currentState, action);\n } finally {\n isDispatching = false;\n }\n\n var listeners = currentListeners = nextListeners;\n\n for (var i = 0; i < listeners.length; i++) {\n var listener = listeners[i];\n listener();\n }\n\n return action;\n }\n /**\n * Replaces the reducer currently used by the store to calculate the state.\n *\n * You might need this if your app implements code splitting and you want to\n * load some of the reducers dynamically. You might also need this if you\n * implement a hot reloading mechanism for Redux.\n *\n * @param {Function} nextReducer The reducer for the store to use instead.\n * @returns {void}\n */\n\n\n function replaceReducer(nextReducer) {\n if (typeof nextReducer !== 'function') {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(10) : \"Expected the nextReducer to be a function. Instead, received: '\" + kindOf(nextReducer));\n }\n\n currentReducer = nextReducer; // This action has a similiar effect to ActionTypes.INIT.\n // Any reducers that existed in both the new and old rootReducer\n // will receive the previous state. This effectively populates\n // the new state tree with any relevant data from the old one.\n\n dispatch({\n type: ActionTypes.REPLACE\n });\n }\n /**\n * Interoperability point for observable/reactive libraries.\n * @returns {observable} A minimal observable of state changes.\n * For more information, see the observable proposal:\n * https://github.com/tc39/proposal-observable\n */\n\n\n function observable() {\n var _ref;\n\n var outerSubscribe = subscribe;\n return _ref = {\n /**\n * The minimal observable subscription method.\n * @param {Object} observer Any object that can be used as an observer.\n * The observer object should have a `next` method.\n * @returns {subscription} An object with an `unsubscribe` method that can\n * be used to unsubscribe the observable from the store, and prevent further\n * emission of values from the observable.\n */\n subscribe: function subscribe(observer) {\n if (typeof observer !== 'object' || observer === null) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(11) : \"Expected the observer to be an object. Instead, received: '\" + kindOf(observer) + \"'\");\n }\n\n function observeState() {\n if (observer.next) {\n observer.next(getState());\n }\n }\n\n observeState();\n var unsubscribe = outerSubscribe(observeState);\n return {\n unsubscribe: unsubscribe\n };\n }\n }, _ref[$$observable] = function () {\n return this;\n }, _ref;\n } // When a store is created, an \"INIT\" action is dispatched so that every\n // reducer returns their initial state. This effectively populates\n // the initial state tree.\n\n\n dispatch({\n type: ActionTypes.INIT\n });\n return _ref2 = {\n dispatch: dispatch,\n subscribe: subscribe,\n getState: getState,\n replaceReducer: replaceReducer\n }, _ref2[$$observable] = observable, _ref2;\n}\n/**\n * Creates a Redux store that holds the state tree.\n *\n * **We recommend using `configureStore` from the\n * `@reduxjs/toolkit` package**, which replaces `createStore`:\n * **https://redux.js.org/introduction/why-rtk-is-redux-today**\n *\n * The only way to change the data in the store is to call `dispatch()` on it.\n *\n * There should only be a single store in your app. To specify how different\n * parts of the state tree respond to actions, you may combine several reducers\n * into a single reducer function by using `combineReducers`.\n *\n * @param {Function} reducer A function that returns the next state tree, given\n * the current state tree and the action to handle.\n *\n * @param {any} [preloadedState] The initial state. You may optionally specify it\n * to hydrate the state from the server in universal apps, or to restore a\n * previously serialized user session.\n * If you use `combineReducers` to produce the root reducer function, this must be\n * an object with the same shape as `combineReducers` keys.\n *\n * @param {Function} [enhancer] The store enhancer. You may optionally specify it\n * to enhance the store with third-party capabilities such as middleware,\n * time travel, persistence, etc. The only store enhancer that ships with Redux\n * is `applyMiddleware()`.\n *\n * @returns {Store} A Redux store that lets you read the state, dispatch actions\n * and subscribe to changes.\n */\n\nvar legacy_createStore = createStore;\n\n/**\n * Prints a warning in the console if it exists.\n *\n * @param {String} message The warning message.\n * @returns {void}\n */\nfunction warning(message) {\n /* eslint-disable no-console */\n if (typeof console !== 'undefined' && typeof console.error === 'function') {\n console.error(message);\n }\n /* eslint-enable no-console */\n\n\n try {\n // This error was thrown as a convenience so that if you enable\n // \"break on all exceptions\" in your console,\n // it would pause the execution at this line.\n throw new Error(message);\n } catch (e) {} // eslint-disable-line no-empty\n\n}\n\nfunction getUnexpectedStateShapeWarningMessage(inputState, reducers, action, unexpectedKeyCache) {\n var reducerKeys = Object.keys(reducers);\n var argumentName = action && action.type === ActionTypes.INIT ? 'preloadedState argument passed to createStore' : 'previous state received by the reducer';\n\n if (reducerKeys.length === 0) {\n return 'Store does not have a valid reducer. Make sure the argument passed ' + 'to combineReducers is an object whose values are reducers.';\n }\n\n if (!isPlainObject(inputState)) {\n return \"The \" + argumentName + \" has unexpected type of \\\"\" + kindOf(inputState) + \"\\\". Expected argument to be an object with the following \" + (\"keys: \\\"\" + reducerKeys.join('\", \"') + \"\\\"\");\n }\n\n var unexpectedKeys = Object.keys(inputState).filter(function (key) {\n return !reducers.hasOwnProperty(key) && !unexpectedKeyCache[key];\n });\n unexpectedKeys.forEach(function (key) {\n unexpectedKeyCache[key] = true;\n });\n if (action && action.type === ActionTypes.REPLACE) return;\n\n if (unexpectedKeys.length > 0) {\n return \"Unexpected \" + (unexpectedKeys.length > 1 ? 'keys' : 'key') + \" \" + (\"\\\"\" + unexpectedKeys.join('\", \"') + \"\\\" found in \" + argumentName + \". \") + \"Expected to find one of the known reducer keys instead: \" + (\"\\\"\" + reducerKeys.join('\", \"') + \"\\\". Unexpected keys will be ignored.\");\n }\n}\n\nfunction assertReducerShape(reducers) {\n Object.keys(reducers).forEach(function (key) {\n var reducer = reducers[key];\n var initialState = reducer(undefined, {\n type: ActionTypes.INIT\n });\n\n if (typeof initialState === 'undefined') {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(12) : \"The slice reducer for key \\\"\" + key + \"\\\" returned undefined during initialization. \" + \"If the state passed to the reducer is undefined, you must \" + \"explicitly return the initial state. The initial state may \" + \"not be undefined. If you don't want to set a value for this reducer, \" + \"you can use null instead of undefined.\");\n }\n\n if (typeof reducer(undefined, {\n type: ActionTypes.PROBE_UNKNOWN_ACTION()\n }) === 'undefined') {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(13) : \"The slice reducer for key \\\"\" + key + \"\\\" returned undefined when probed with a random type. \" + (\"Don't try to handle '\" + ActionTypes.INIT + \"' or other actions in \\\"redux/*\\\" \") + \"namespace. They are considered private. Instead, you must return the \" + \"current state for any unknown actions, unless it is undefined, \" + \"in which case you must return the initial state, regardless of the \" + \"action type. The initial state may not be undefined, but can be null.\");\n }\n });\n}\n/**\n * Turns an object whose values are different reducer functions, into a single\n * reducer function. It will call every child reducer, and gather their results\n * into a single state object, whose keys correspond to the keys of the passed\n * reducer functions.\n *\n * @param {Object} reducers An object whose values correspond to different\n * reducer functions that need to be combined into one. One handy way to obtain\n * it is to use ES6 `import * as reducers` syntax. The reducers may never return\n * undefined for any action. Instead, they should return their initial state\n * if the state passed to them was undefined, and the current state for any\n * unrecognized action.\n *\n * @returns {Function} A reducer function that invokes every reducer inside the\n * passed object, and builds a state object with the same shape.\n */\n\n\nfunction combineReducers(reducers) {\n var reducerKeys = Object.keys(reducers);\n var finalReducers = {};\n\n for (var i = 0; i < reducerKeys.length; i++) {\n var key = reducerKeys[i];\n\n if (process.env.NODE_ENV !== 'production') {\n if (typeof reducers[key] === 'undefined') {\n warning(\"No reducer provided for key \\\"\" + key + \"\\\"\");\n }\n }\n\n if (typeof reducers[key] === 'function') {\n finalReducers[key] = reducers[key];\n }\n }\n\n var finalReducerKeys = Object.keys(finalReducers); // This is used to make sure we don't warn about the same\n // keys multiple times.\n\n var unexpectedKeyCache;\n\n if (process.env.NODE_ENV !== 'production') {\n unexpectedKeyCache = {};\n }\n\n var shapeAssertionError;\n\n try {\n assertReducerShape(finalReducers);\n } catch (e) {\n shapeAssertionError = e;\n }\n\n return function combination(state, action) {\n if (state === void 0) {\n state = {};\n }\n\n if (shapeAssertionError) {\n throw shapeAssertionError;\n }\n\n if (process.env.NODE_ENV !== 'production') {\n var warningMessage = getUnexpectedStateShapeWarningMessage(state, finalReducers, action, unexpectedKeyCache);\n\n if (warningMessage) {\n warning(warningMessage);\n }\n }\n\n var hasChanged = false;\n var nextState = {};\n\n for (var _i = 0; _i < finalReducerKeys.length; _i++) {\n var _key = finalReducerKeys[_i];\n var reducer = finalReducers[_key];\n var previousStateForKey = state[_key];\n var nextStateForKey = reducer(previousStateForKey, action);\n\n if (typeof nextStateForKey === 'undefined') {\n var actionType = action && action.type;\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(14) : \"When called with an action of type \" + (actionType ? \"\\\"\" + String(actionType) + \"\\\"\" : '(unknown type)') + \", the slice reducer for key \\\"\" + _key + \"\\\" returned undefined. \" + \"To ignore an action, you must explicitly return the previous state. \" + \"If you want this reducer to hold no value, you can return null instead of undefined.\");\n }\n\n nextState[_key] = nextStateForKey;\n hasChanged = hasChanged || nextStateForKey !== previousStateForKey;\n }\n\n hasChanged = hasChanged || finalReducerKeys.length !== Object.keys(state).length;\n return hasChanged ? nextState : state;\n };\n}\n\nfunction bindActionCreator(actionCreator, dispatch) {\n return function () {\n return dispatch(actionCreator.apply(this, arguments));\n };\n}\n/**\n * Turns an object whose values are action creators, into an object with the\n * same keys, but with every function wrapped into a `dispatch` call so they\n * may be invoked directly. This is just a convenience method, as you can call\n * `store.dispatch(MyActionCreators.doSomething())` yourself just fine.\n *\n * For convenience, you can also pass an action creator as the first argument,\n * and get a dispatch wrapped function in return.\n *\n * @param {Function|Object} actionCreators An object whose values are action\n * creator functions. One handy way to obtain it is to use ES6 `import * as`\n * syntax. You may also pass a single function.\n *\n * @param {Function} dispatch The `dispatch` function available on your Redux\n * store.\n *\n * @returns {Function|Object} The object mimicking the original object, but with\n * every action creator wrapped into the `dispatch` call. If you passed a\n * function as `actionCreators`, the return value will also be a single\n * function.\n */\n\n\nfunction bindActionCreators(actionCreators, dispatch) {\n if (typeof actionCreators === 'function') {\n return bindActionCreator(actionCreators, dispatch);\n }\n\n if (typeof actionCreators !== 'object' || actionCreators === null) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(16) : \"bindActionCreators expected an object or a function, but instead received: '\" + kindOf(actionCreators) + \"'. \" + \"Did you write \\\"import ActionCreators from\\\" instead of \\\"import * as ActionCreators from\\\"?\");\n }\n\n var boundActionCreators = {};\n\n for (var key in actionCreators) {\n var actionCreator = actionCreators[key];\n\n if (typeof actionCreator === 'function') {\n boundActionCreators[key] = bindActionCreator(actionCreator, dispatch);\n }\n }\n\n return boundActionCreators;\n}\n\n/**\n * Composes single-argument functions from right to left. The rightmost\n * function can take multiple arguments as it provides the signature for\n * the resulting composite function.\n *\n * @param {...Function} funcs The functions to compose.\n * @returns {Function} A function obtained by composing the argument functions\n * from right to left. For example, compose(f, g, h) is identical to doing\n * (...args) => f(g(h(...args))).\n */\nfunction compose() {\n for (var _len = arguments.length, funcs = new Array(_len), _key = 0; _key < _len; _key++) {\n funcs[_key] = arguments[_key];\n }\n\n if (funcs.length === 0) {\n return function (arg) {\n return arg;\n };\n }\n\n if (funcs.length === 1) {\n return funcs[0];\n }\n\n return funcs.reduce(function (a, b) {\n return function () {\n return a(b.apply(void 0, arguments));\n };\n });\n}\n\n/**\n * Creates a store enhancer that applies middleware to the dispatch method\n * of the Redux store. This is handy for a variety of tasks, such as expressing\n * asynchronous actions in a concise manner, or logging every action payload.\n *\n * See `redux-thunk` package as an example of the Redux middleware.\n *\n * Because middleware is potentially asynchronous, this should be the first\n * store enhancer in the composition chain.\n *\n * Note that each middleware will be given the `dispatch` and `getState` functions\n * as named arguments.\n *\n * @param {...Function} middlewares The middleware chain to be applied.\n * @returns {Function} A store enhancer applying the middleware.\n */\n\nfunction applyMiddleware() {\n for (var _len = arguments.length, middlewares = new Array(_len), _key = 0; _key < _len; _key++) {\n middlewares[_key] = arguments[_key];\n }\n\n return function (createStore) {\n return function () {\n var store = createStore.apply(void 0, arguments);\n\n var _dispatch = function dispatch() {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(15) : 'Dispatching while constructing your middleware is not allowed. ' + 'Other middleware would not be applied to this dispatch.');\n };\n\n var middlewareAPI = {\n getState: store.getState,\n dispatch: function dispatch() {\n return _dispatch.apply(void 0, arguments);\n }\n };\n var chain = middlewares.map(function (middleware) {\n return middleware(middlewareAPI);\n });\n _dispatch = compose.apply(void 0, chain)(store.dispatch);\n return _objectSpread(_objectSpread({}, store), {}, {\n dispatch: _dispatch\n });\n };\n };\n}\n\nexport { ActionTypes as __DO_NOT_USE__ActionTypes, applyMiddleware, bindActionCreators, combineReducers, compose, createStore, legacy_createStore };\n", "/** A function that accepts a potential \"extra argument\" value to be injected later,\r\n * and returns an instance of the thunk middleware that uses that value\r\n */\nfunction createThunkMiddleware(extraArgument) {\n // Standard Redux middleware definition pattern:\n // See: https://redux.js.org/tutorials/fundamentals/part-4-store#writing-custom-middleware\n var middleware = function middleware(_ref) {\n var dispatch = _ref.dispatch,\n getState = _ref.getState;\n return function (next) {\n return function (action) {\n // The thunk middleware looks for any functions that were passed to `store.dispatch`.\n // If this \"action\" is really a function, call it and return the result.\n if (typeof action === 'function') {\n // Inject the store's `dispatch` and `getState` methods, as well as any \"extra arg\"\n return action(dispatch, getState, extraArgument);\n } // Otherwise, pass the action down the middleware chain as usual\n\n\n return next(action);\n };\n };\n };\n\n return middleware;\n}\n\nvar thunk = createThunkMiddleware(); // Attach the factory function so users can create a customized version\n// with whatever \"extra arg\" they want to inject into their thunks\n\nthunk.withExtraArgument = createThunkMiddleware;\nexport default thunk;", "import { enableES5 } from 'immer'\r\nexport * from 'redux'\r\nexport {\r\n default as createNextState,\r\n current,\r\n freeze,\r\n original,\r\n isDraft,\r\n} from 'immer'\r\nexport type { Draft } from 'immer'\r\nexport { createSelector } from 'reselect'\r\nexport type {\r\n Selector,\r\n OutputParametricSelector,\r\n OutputSelector,\r\n ParametricSelector,\r\n} from 'reselect'\r\nexport { createDraftSafeSelector } from './createDraftSafeSelector'\r\nexport type { ThunkAction, ThunkDispatch, ThunkMiddleware } from 'redux-thunk'\r\n\r\n// We deliberately enable Immer's ES5 support, on the grounds that\r\n// we assume RTK will be used with React Native and other Proxy-less\r\n// environments. In addition, that's how Immer 4 behaved, and since\r\n// we want to ship this in an RTK minor, we should keep the same behavior.\r\nenableES5()\r\n\r\nexport {\r\n // js\r\n configureStore,\r\n} from './configureStore'\r\nexport type {\r\n // types\r\n ConfigureEnhancersCallback,\r\n ConfigureStoreOptions,\r\n EnhancedStore,\r\n} from './configureStore'\r\nexport type { DevToolsEnhancerOptions } from './devtoolsExtension'\r\nexport {\r\n // js\r\n createAction,\r\n getType,\r\n isAction,\r\n isActionCreator,\r\n isFSA as isFluxStandardAction,\r\n} from './createAction'\r\nexport type {\r\n // types\r\n PayloadAction,\r\n PayloadActionCreator,\r\n ActionCreatorWithNonInferrablePayload,\r\n ActionCreatorWithOptionalPayload,\r\n ActionCreatorWithPayload,\r\n ActionCreatorWithoutPayload,\r\n ActionCreatorWithPreparedPayload,\r\n PrepareAction,\r\n} from './createAction'\r\nexport {\r\n // js\r\n createReducer,\r\n} from './createReducer'\r\nexport type {\r\n // types\r\n Actions,\r\n CaseReducer,\r\n CaseReducers,\r\n} from './createReducer'\r\nexport {\r\n // js\r\n createSlice,\r\n} from './createSlice'\r\n\r\nexport type {\r\n // types\r\n CreateSliceOptions,\r\n Slice,\r\n CaseReducerActions,\r\n SliceCaseReducers,\r\n ValidateSliceCaseReducers,\r\n CaseReducerWithPrepare,\r\n SliceActionCreator,\r\n} from './createSlice'\r\nexport type { ActionCreatorInvariantMiddlewareOptions } from './actionCreatorInvariantMiddleware'\r\nexport { createActionCreatorInvariantMiddleware } from './actionCreatorInvariantMiddleware'\r\nexport {\r\n // js\r\n createImmutableStateInvariantMiddleware,\r\n isImmutableDefault,\r\n} from './immutableStateInvariantMiddleware'\r\nexport type {\r\n // types\r\n ImmutableStateInvariantMiddlewareOptions,\r\n} from './immutableStateInvariantMiddleware'\r\nexport {\r\n // js\r\n createSerializableStateInvariantMiddleware,\r\n findNonSerializableValue,\r\n isPlain,\r\n} from './serializableStateInvariantMiddleware'\r\nexport type {\r\n // types\r\n SerializableStateInvariantMiddlewareOptions,\r\n} from './serializableStateInvariantMiddleware'\r\nexport {\r\n // js\r\n getDefaultMiddleware,\r\n} from './getDefaultMiddleware'\r\nexport type {\r\n // types\r\n ActionReducerMapBuilder,\r\n} from './mapBuilders'\r\nexport { MiddlewareArray, EnhancerArray } from './utils'\r\n\r\nexport { createEntityAdapter } from './entities/create_adapter'\r\nexport type {\r\n Dictionary,\r\n EntityState,\r\n EntityAdapter,\r\n EntitySelectors,\r\n EntityStateAdapter,\r\n EntityId,\r\n Update,\r\n IdSelector,\r\n Comparer,\r\n} from './entities/models'\r\n\r\nexport {\r\n createAsyncThunk,\r\n unwrapResult,\r\n miniSerializeError,\r\n} from './createAsyncThunk'\r\nexport type {\r\n AsyncThunk,\r\n AsyncThunkOptions,\r\n AsyncThunkAction,\r\n AsyncThunkPayloadCreatorReturnValue,\r\n AsyncThunkPayloadCreator,\r\n SerializedError,\r\n} from './createAsyncThunk'\r\n\r\nexport {\r\n // js\r\n isAllOf,\r\n isAnyOf,\r\n isPending,\r\n isRejected,\r\n isFulfilled,\r\n isAsyncThunkAction,\r\n isRejectedWithValue,\r\n} from './matchers'\r\nexport type {\r\n // types\r\n ActionMatchingAllOf,\r\n ActionMatchingAnyOf,\r\n} from './matchers'\r\n\r\nexport { nanoid } from './nanoid'\r\n\r\nexport { default as isPlainObject } from './isPlainObject'\r\n\r\nexport type {\r\n ListenerEffect,\r\n ListenerMiddleware,\r\n ListenerEffectAPI,\r\n ListenerMiddlewareInstance,\r\n CreateListenerMiddlewareOptions,\r\n ListenerErrorHandler,\r\n TypedStartListening,\r\n TypedAddListener,\r\n TypedStopListening,\r\n TypedRemoveListener,\r\n UnsubscribeListener,\r\n UnsubscribeListenerOptions,\r\n ForkedTaskExecutor,\r\n ForkedTask,\r\n ForkedTaskAPI,\r\n AsyncTaskExecutor,\r\n SyncTaskExecutor,\r\n TaskCancelled,\r\n TaskRejected,\r\n TaskResolved,\r\n TaskResult,\r\n} from './listenerMiddleware/index'\r\nexport type { AnyListenerPredicate } from './listenerMiddleware/types'\r\n\r\nexport {\r\n createListenerMiddleware,\r\n addListener,\r\n removeListener,\r\n clearAllListeners,\r\n TaskAbortError,\r\n} from './listenerMiddleware/index'\r\n\r\nexport {\r\n SHOULD_AUTOBATCH,\r\n prepareAutoBatched,\r\n autoBatchEnhancer,\r\n} from './autoBatchEnhancer'\r\nexport type { AutoBatchOptions } from './autoBatchEnhancer'\r\n\r\nexport type { ExtractDispatchExtensions as TSHelpersExtractDispatchExtensions } from './tsHelpers'\r\n", "import { current, isDraft } from 'immer'\r\nimport { createSelector } from 'reselect'\r\n\r\n/**\r\n * \"Draft-Safe\" version of `reselect`'s `createSelector`:\r\n * If an `immer`-drafted object is passed into the resulting selector's first argument,\r\n * the selector will act on the current draft value, instead of returning a cached value\r\n * that might be possibly outdated if the draft has been modified since.\r\n * @public\r\n */\r\nexport const createDraftSafeSelector: typeof createSelector = (\r\n ...args: unknown[]\r\n) => {\r\n const selector = (createSelector as any)(...args)\r\n const wrappedSelector = (value: unknown, ...rest: unknown[]) =>\r\n selector(isDraft(value) ? current(value) : value, ...rest)\r\n return wrappedSelector as any\r\n}\r\n", "import type {\r\n Reducer,\r\n ReducersMapObject,\r\n Middleware,\r\n Action,\r\n AnyAction,\r\n StoreEnhancer,\r\n Store,\r\n Dispatch,\r\n PreloadedState,\r\n CombinedState,\r\n} from 'redux'\r\nimport { createStore, compose, applyMiddleware, combineReducers } from 'redux'\r\nimport type { DevToolsEnhancerOptions as DevToolsOptions } from './devtoolsExtension'\r\nimport { composeWithDevTools } from './devtoolsExtension'\r\n\r\nimport isPlainObject from './isPlainObject'\r\nimport type {\r\n ThunkMiddlewareFor,\r\n CurriedGetDefaultMiddleware,\r\n} from './getDefaultMiddleware'\r\nimport { curryGetDefaultMiddleware } from './getDefaultMiddleware'\r\nimport type {\r\n NoInfer,\r\n ExtractDispatchExtensions,\r\n ExtractStoreExtensions,\r\n ExtractStateExtensions,\r\n} from './tsHelpers'\r\nimport { EnhancerArray } from './utils'\r\n\r\nconst IS_PRODUCTION = process.env.NODE_ENV === 'production'\r\n\r\n/**\r\n * Callback function type, to be used in `ConfigureStoreOptions.enhancers`\r\n *\r\n * @public\r\n */\r\nexport type ConfigureEnhancersCallback = (\r\n defaultEnhancers: EnhancerArray<[StoreEnhancer<{}, {}>]>\r\n) => E\r\n\r\n/**\r\n * Options for `configureStore()`.\r\n *\r\n * @public\r\n */\r\nexport interface ConfigureStoreOptions<\r\n S = any,\r\n A extends Action = AnyAction,\r\n M extends Middlewares = Middlewares,\r\n E extends Enhancers = Enhancers\r\n> {\r\n /**\r\n * A single reducer function that will be used as the root reducer, or an\r\n * object of slice reducers that will be passed to `combineReducers()`.\r\n */\r\n reducer: Reducer | ReducersMapObject\r\n\r\n /**\r\n * An array of Redux middleware to install. If not supplied, defaults to\r\n * the set of middleware returned by `getDefaultMiddleware()`.\r\n *\r\n * @example `middleware: (gDM) => gDM().concat(logger, apiMiddleware, yourCustomMiddleware)`\r\n * @see https://redux-toolkit.js.org/api/getDefaultMiddleware#intended-usage\r\n */\r\n middleware?: ((getDefaultMiddleware: CurriedGetDefaultMiddleware) => M) | M\r\n\r\n /**\r\n * Whether to enable Redux DevTools integration. Defaults to `true`.\r\n *\r\n * Additional configuration can be done by passing Redux DevTools options\r\n */\r\n devTools?: boolean | DevToolsOptions\r\n\r\n /**\r\n * The initial state, same as Redux's createStore.\r\n * You may optionally specify it to hydrate the state\r\n * from the server in universal apps, or to restore a previously serialized\r\n * user session. If you use `combineReducers()` to produce the root reducer\r\n * function (either directly or indirectly by passing an object as `reducer`),\r\n * this must be an object with the same shape as the reducer map keys.\r\n */\r\n /*\r\n Not 100% correct but the best approximation we can get:\r\n - if S is a `CombinedState` applying a second `CombinedState` on it does not change anything.\r\n - if it is not, there could be two cases:\r\n - `ReducersMapObject` is being passed in. In this case, we will call `combineReducers` on it and `CombinedState` is correct\r\n - `Reducer` is being passed in. In this case, actually `CombinedState` is wrong and `S` would be correct.\r\n As we cannot distinguish between those two cases without adding another generic parameter,\r\n we just make the pragmatic assumption that the latter almost never happens.\r\n */\r\n preloadedState?: PreloadedState>>\r\n\r\n /**\r\n * The store enhancers to apply. See Redux's `createStore()`.\r\n * All enhancers will be included before the DevTools Extension enhancer.\r\n * If you need to customize the order of enhancers, supply a callback\r\n * function that will receive the original array (ie, `[applyMiddleware]`),\r\n * and should return a new array (such as `[applyMiddleware, offline]`).\r\n * If you only need to add middleware, you can use the `middleware` parameter instead.\r\n */\r\n enhancers?: E | ConfigureEnhancersCallback\r\n}\r\n\r\ntype Middlewares = ReadonlyArray>\r\n\r\ntype Enhancers = ReadonlyArray\r\n\r\nexport interface ToolkitStore<\r\n S = any,\r\n A extends Action = AnyAction,\r\n M extends Middlewares = Middlewares\r\n> extends Store {\r\n /**\r\n * The `dispatch` method of your store, enhanced by all its middlewares.\r\n *\r\n * @inheritdoc\r\n */\r\n dispatch: ExtractDispatchExtensions & Dispatch\r\n}\r\n\r\n/**\r\n * A Redux store returned by `configureStore()`. Supports dispatching\r\n * side-effectful _thunks_ in addition to plain actions.\r\n *\r\n * @public\r\n */\r\nexport type EnhancedStore<\r\n S = any,\r\n A extends Action = AnyAction,\r\n M extends Middlewares = Middlewares,\r\n E extends Enhancers = Enhancers\r\n> = ToolkitStore, A, M> &\r\n ExtractStoreExtensions\r\n\r\n/**\r\n * A friendly abstraction over the standard Redux `createStore()` function.\r\n *\r\n * @param options The store configuration.\r\n * @returns A configured Redux store.\r\n *\r\n * @public\r\n */\r\nexport function configureStore<\r\n S = any,\r\n A extends Action = AnyAction,\r\n M extends Middlewares = [ThunkMiddlewareFor],\r\n E extends Enhancers = [StoreEnhancer]\r\n>(options: ConfigureStoreOptions): EnhancedStore {\r\n const curriedGetDefaultMiddleware = curryGetDefaultMiddleware()\r\n\r\n const {\r\n reducer = undefined,\r\n middleware = curriedGetDefaultMiddleware(),\r\n devTools = true,\r\n preloadedState = undefined,\r\n enhancers = undefined,\r\n } = options || {}\r\n\r\n let rootReducer: Reducer\r\n\r\n if (typeof reducer === 'function') {\r\n rootReducer = reducer\r\n } else if (isPlainObject(reducer)) {\r\n rootReducer = combineReducers(reducer) as unknown as Reducer\r\n } else {\r\n throw new Error(\r\n '\"reducer\" is a required argument, and must be a function or an object of functions that can be passed to combineReducers'\r\n )\r\n }\r\n\r\n let finalMiddleware = middleware\r\n if (typeof finalMiddleware === 'function') {\r\n finalMiddleware = finalMiddleware(curriedGetDefaultMiddleware)\r\n\r\n if (!IS_PRODUCTION && !Array.isArray(finalMiddleware)) {\r\n throw new Error(\r\n 'when using a middleware builder function, an array of middleware must be returned'\r\n )\r\n }\r\n }\r\n if (\r\n !IS_PRODUCTION &&\r\n finalMiddleware.some((item: any) => typeof item !== 'function')\r\n ) {\r\n throw new Error(\r\n 'each middleware provided to configureStore must be a function'\r\n )\r\n }\r\n\r\n const middlewareEnhancer: StoreEnhancer = applyMiddleware(...finalMiddleware)\r\n\r\n let finalCompose = compose\r\n\r\n if (devTools) {\r\n finalCompose = composeWithDevTools({\r\n // Enable capture of stack traces for dispatched Redux actions\r\n trace: !IS_PRODUCTION,\r\n ...(typeof devTools === 'object' && devTools),\r\n })\r\n }\r\n\r\n const defaultEnhancers = new EnhancerArray(middlewareEnhancer)\r\n let storeEnhancers: Enhancers = defaultEnhancers\r\n\r\n if (Array.isArray(enhancers)) {\r\n storeEnhancers = [middlewareEnhancer, ...enhancers]\r\n } else if (typeof enhancers === 'function') {\r\n storeEnhancers = enhancers(defaultEnhancers)\r\n }\r\n\r\n const composedEnhancer = finalCompose(...storeEnhancers) as StoreEnhancer\r\n\r\n return createStore(rootReducer, preloadedState, composedEnhancer)\r\n}\r\n", "import type { Action, ActionCreator, StoreEnhancer } from 'redux'\r\nimport { compose } from 'redux'\r\n\r\n/**\r\n * @public\r\n */\r\nexport interface DevToolsEnhancerOptions {\r\n /**\r\n * the instance name to be showed on the monitor page. Default value is `document.title`.\r\n * If not specified and there's no document title, it will consist of `tabId` and `instanceId`.\r\n */\r\n name?: string\r\n /**\r\n * action creators functions to be available in the Dispatcher.\r\n */\r\n actionCreators?: ActionCreator[] | { [key: string]: ActionCreator }\r\n /**\r\n * if more than one action is dispatched in the indicated interval, all new actions will be collected and sent at once.\r\n * It is the joint between performance and speed. When set to `0`, all actions will be sent instantly.\r\n * Set it to a higher value when experiencing perf issues (also `maxAge` to a lower value).\r\n *\r\n * @default 500 ms.\r\n */\r\n latency?: number\r\n /**\r\n * (> 1) - maximum allowed actions to be stored in the history tree. The oldest actions are removed once maxAge is reached. It's critical for performance.\r\n *\r\n * @default 50\r\n */\r\n maxAge?: number\r\n /**\r\n * Customizes how actions and state are serialized and deserialized. Can be a boolean or object. If given a boolean, the behavior is the same as if you\r\n * were to pass an object and specify `options` as a boolean. Giving an object allows fine-grained customization using the `replacer` and `reviver`\r\n * functions.\r\n */\r\n serialize?:\r\n | boolean\r\n | {\r\n /**\r\n * - `undefined` - will use regular `JSON.stringify` to send data (it's the fast mode).\r\n * - `false` - will handle also circular references.\r\n * - `true` - will handle also date, regex, undefined, error objects, symbols, maps, sets and functions.\r\n * - object, which contains `date`, `regex`, `undefined`, `error`, `symbol`, `map`, `set` and `function` keys.\r\n * For each of them you can indicate if to include (by setting as `true`).\r\n * For `function` key you can also specify a custom function which handles serialization.\r\n * See [`jsan`](https://github.com/kolodny/jsan) for more details.\r\n */\r\n options?:\r\n | undefined\r\n | boolean\r\n | {\r\n date?: true\r\n regex?: true\r\n undefined?: true\r\n error?: true\r\n symbol?: true\r\n map?: true\r\n set?: true\r\n function?: true | ((fn: (...args: any[]) => any) => string)\r\n }\r\n /**\r\n * [JSON replacer function](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_replacer_parameter) used for both actions and states stringify.\r\n * In addition, you can specify a data type by adding a [`__serializedType__`](https://github.com/zalmoxisus/remotedev-serialize/blob/master/helpers/index.js#L4)\r\n * key. So you can deserialize it back while importing or persisting data.\r\n * Moreover, it will also [show a nice preview showing the provided custom type](https://cloud.githubusercontent.com/assets/7957859/21814330/a17d556a-d761-11e6-85ef-159dd12f36c5.png):\r\n */\r\n replacer?: (key: string, value: unknown) => any\r\n /**\r\n * [JSON `reviver` function](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Using_the_reviver_parameter)\r\n * used for parsing the imported actions and states. See [`remotedev-serialize`](https://github.com/zalmoxisus/remotedev-serialize/blob/master/immutable/serialize.js#L8-L41)\r\n * as an example on how to serialize special data types and get them back.\r\n */\r\n reviver?: (key: string, value: unknown) => any\r\n /**\r\n * Automatically serialize/deserialize immutablejs via [remotedev-serialize](https://github.com/zalmoxisus/remotedev-serialize).\r\n * Just pass the Immutable library. It will support all ImmutableJS structures. You can even export them into a file and get them back.\r\n * The only exception is `Record` class, for which you should pass this in addition the references to your classes in `refs`.\r\n */\r\n immutable?: any\r\n /**\r\n * ImmutableJS `Record` classes used to make possible restore its instances back when importing, persisting...\r\n */\r\n refs?: any\r\n }\r\n /**\r\n * function which takes `action` object and id number as arguments, and should return `action` object back.\r\n */\r\n actionSanitizer?: (action: A, id: number) => A\r\n /**\r\n * function which takes `state` object and index as arguments, and should return `state` object back.\r\n */\r\n stateSanitizer?: (state: S, index: number) => S\r\n /**\r\n * *string or array of strings as regex* - actions types to be hidden / shown in the monitors (while passed to the reducers).\r\n * If `actionsWhitelist` specified, `actionsBlacklist` is ignored.\r\n * @deprecated Use actionsDenylist instead.\r\n */\r\n actionsBlacklist?: string | string[]\r\n /**\r\n * *string or array of strings as regex* - actions types to be hidden / shown in the monitors (while passed to the reducers).\r\n * If `actionsWhitelist` specified, `actionsBlacklist` is ignored.\r\n * @deprecated Use actionsAllowlist instead.\r\n */\r\n actionsWhitelist?: string | string[]\r\n /**\r\n * *string or array of strings as regex* - actions types to be hidden / shown in the monitors (while passed to the reducers).\r\n * If `actionsAllowlist` specified, `actionsDenylist` is ignored.\r\n */\r\n actionsDenylist?: string | string[]\r\n /**\r\n * *string or array of strings as regex* - actions types to be hidden / shown in the monitors (while passed to the reducers).\r\n * If `actionsAllowlist` specified, `actionsDenylist` is ignored.\r\n */\r\n actionsAllowlist?: string | string[]\r\n /**\r\n * called for every action before sending, takes `state` and `action` object, and returns `true` in case it allows sending the current data to the monitor.\r\n * Use it as a more advanced version of `actionsDenylist`/`actionsAllowlist` parameters.\r\n */\r\n predicate?: (state: S, action: A) => boolean\r\n /**\r\n * if specified as `false`, it will not record the changes till clicking on `Start recording` button.\r\n * Available only for Redux enhancer, for others use `autoPause`.\r\n *\r\n * @default true\r\n */\r\n shouldRecordChanges?: boolean\r\n /**\r\n * if specified, whenever clicking on `Pause recording` button and there are actions in the history log, will add this action type.\r\n * If not specified, will commit when paused. Available only for Redux enhancer.\r\n *\r\n * @default \"@@PAUSED\"\"\r\n */\r\n pauseActionType?: string\r\n /**\r\n * auto pauses when the extension’s window is not opened, and so has zero impact on your app when not in use.\r\n * Not available for Redux enhancer (as it already does it but storing the data to be sent).\r\n *\r\n * @default false\r\n */\r\n autoPause?: boolean\r\n /**\r\n * if specified as `true`, it will not allow any non-monitor actions to be dispatched till clicking on `Unlock changes` button.\r\n * Available only for Redux enhancer.\r\n *\r\n * @default false\r\n */\r\n shouldStartLocked?: boolean\r\n /**\r\n * if set to `false`, will not recompute the states on hot reloading (or on replacing the reducers). Available only for Redux enhancer.\r\n *\r\n * @default true\r\n */\r\n shouldHotReload?: boolean\r\n /**\r\n * if specified as `true`, whenever there's an exception in reducers, the monitors will show the error message, and next actions will not be dispatched.\r\n *\r\n * @default false\r\n */\r\n shouldCatchErrors?: boolean\r\n /**\r\n * If you want to restrict the extension, specify the features you allow.\r\n * If not specified, all of the features are enabled. When set as an object, only those included as `true` will be allowed.\r\n * Note that except `true`/`false`, `import` and `export` can be set as `custom` (which is by default for Redux enhancer), meaning that the importing/exporting occurs on the client side.\r\n * Otherwise, you'll get/set the data right from the monitor part.\r\n */\r\n features?: {\r\n /**\r\n * start/pause recording of dispatched actions\r\n */\r\n pause?: boolean\r\n /**\r\n * lock/unlock dispatching actions and side effects\r\n */\r\n lock?: boolean\r\n /**\r\n * persist states on page reloading\r\n */\r\n persist?: boolean\r\n /**\r\n * export history of actions in a file\r\n */\r\n export?: boolean | 'custom'\r\n /**\r\n * import history of actions from a file\r\n */\r\n import?: boolean | 'custom'\r\n /**\r\n * jump back and forth (time travelling)\r\n */\r\n jump?: boolean\r\n /**\r\n * skip (cancel) actions\r\n */\r\n skip?: boolean\r\n /**\r\n * drag and drop actions in the history list\r\n */\r\n reorder?: boolean\r\n /**\r\n * dispatch custom actions or action creators\r\n */\r\n dispatch?: boolean\r\n /**\r\n * generate tests for the selected actions\r\n */\r\n test?: boolean\r\n }\r\n /**\r\n * Set to true or a stacktrace-returning function to record call stack traces for dispatched actions.\r\n * Defaults to false.\r\n */\r\n trace?: boolean | ((action: A) => string)\r\n /**\r\n * The maximum number of stack trace entries to record per action. Defaults to 10.\r\n */\r\n traceLimit?: number\r\n}\r\n\r\ntype Compose = typeof compose\r\n\r\ninterface ComposeWithDevTools {\r\n (options: DevToolsEnhancerOptions): Compose\r\n (...funcs: StoreEnhancer[]): StoreEnhancer\r\n}\r\n\r\n/**\r\n * @public\r\n */\r\nexport const composeWithDevTools: ComposeWithDevTools =\r\n typeof window !== 'undefined' &&\r\n (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__\r\n ? (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__\r\n : function () {\r\n if (arguments.length === 0) return undefined\r\n if (typeof arguments[0] === 'object') return compose\r\n return compose.apply(null, arguments as any as Function[])\r\n }\r\n\r\n/**\r\n * @public\r\n */\r\nexport const devToolsEnhancer: {\r\n (options: DevToolsEnhancerOptions): StoreEnhancer\r\n} =\r\n typeof window !== 'undefined' && (window as any).__REDUX_DEVTOOLS_EXTENSION__\r\n ? (window as any).__REDUX_DEVTOOLS_EXTENSION__\r\n : function () {\r\n return function (noop) {\r\n return noop\r\n }\r\n }\r\n", "/**\r\n * Returns true if the passed value is \"plain\" object, i.e. an object whose\r\n * prototype is the root `Object.prototype`. This includes objects created\r\n * using object literals, but not for instance for class instances.\r\n *\r\n * @param {any} value The value to inspect.\r\n * @returns {boolean} True if the argument appears to be a plain object.\r\n *\r\n * @public\r\n */\r\nexport default function isPlainObject(value: unknown): value is object {\r\n if (typeof value !== 'object' || value === null) return false\r\n\r\n let proto = Object.getPrototypeOf(value)\r\n if (proto === null) return true\r\n\r\n let baseProto = proto\r\n while (Object.getPrototypeOf(baseProto) !== null) {\r\n baseProto = Object.getPrototypeOf(baseProto)\r\n }\r\n\r\n return proto === baseProto\r\n}\r\n", "import type { Middleware, AnyAction } from 'redux'\r\nimport type { ThunkMiddleware } from 'redux-thunk'\r\nimport thunkMiddleware from 'redux-thunk'\r\nimport type { ActionCreatorInvariantMiddlewareOptions } from './actionCreatorInvariantMiddleware'\r\nimport { createActionCreatorInvariantMiddleware } from './actionCreatorInvariantMiddleware'\r\nimport type { ImmutableStateInvariantMiddlewareOptions } from './immutableStateInvariantMiddleware'\r\n/* PROD_START_REMOVE_UMD */\r\nimport { createImmutableStateInvariantMiddleware } from './immutableStateInvariantMiddleware'\r\n/* PROD_STOP_REMOVE_UMD */\r\n\r\nimport type { SerializableStateInvariantMiddlewareOptions } from './serializableStateInvariantMiddleware'\r\nimport { createSerializableStateInvariantMiddleware } from './serializableStateInvariantMiddleware'\r\nimport type { ExcludeFromTuple } from './tsHelpers'\r\nimport { MiddlewareArray } from './utils'\r\n\r\nfunction isBoolean(x: any): x is boolean {\r\n return typeof x === 'boolean'\r\n}\r\n\r\ninterface ThunkOptions {\r\n extraArgument: E\r\n}\r\n\r\ninterface GetDefaultMiddlewareOptions {\r\n thunk?: boolean | ThunkOptions\r\n immutableCheck?: boolean | ImmutableStateInvariantMiddlewareOptions\r\n serializableCheck?: boolean | SerializableStateInvariantMiddlewareOptions\r\n actionCreatorCheck?: boolean | ActionCreatorInvariantMiddlewareOptions\r\n}\r\n\r\nexport type ThunkMiddlewareFor<\r\n S,\r\n O extends GetDefaultMiddlewareOptions = {}\r\n> = O extends {\r\n thunk: false\r\n}\r\n ? never\r\n : O extends { thunk: { extraArgument: infer E } }\r\n ? ThunkMiddleware\r\n : ThunkMiddleware\r\n\r\nexport type CurriedGetDefaultMiddleware = <\r\n O extends Partial = {\r\n thunk: true\r\n immutableCheck: true\r\n serializableCheck: true\r\n actionCreatorCheck: true\r\n }\r\n>(\r\n options?: O\r\n) => MiddlewareArray], never>>\r\n\r\nexport function curryGetDefaultMiddleware<\r\n S = any\r\n>(): CurriedGetDefaultMiddleware {\r\n return function curriedGetDefaultMiddleware(options) {\r\n return getDefaultMiddleware(options)\r\n }\r\n}\r\n\r\n/**\r\n * Returns any array containing the default middleware installed by\r\n * `configureStore()`. Useful if you want to configure your store with a custom\r\n * `middleware` array but still keep the default set.\r\n *\r\n * @return The default middleware used by `configureStore()`.\r\n *\r\n * @public\r\n *\r\n * @deprecated Prefer to use the callback notation for the `middleware` option in `configureStore`\r\n * to access a pre-typed `getDefaultMiddleware` instead.\r\n */\r\nexport function getDefaultMiddleware<\r\n S = any,\r\n O extends Partial = {\r\n thunk: true\r\n immutableCheck: true\r\n serializableCheck: true\r\n actionCreatorCheck: true\r\n }\r\n>(\r\n options: O = {} as O\r\n): MiddlewareArray], never>> {\r\n const {\r\n thunk = true,\r\n immutableCheck = true,\r\n serializableCheck = true,\r\n actionCreatorCheck = true,\r\n } = options\r\n\r\n let middlewareArray = new MiddlewareArray()\r\n\r\n if (thunk) {\r\n if (isBoolean(thunk)) {\r\n middlewareArray.push(thunkMiddleware)\r\n } else {\r\n middlewareArray.push(\r\n thunkMiddleware.withExtraArgument(thunk.extraArgument)\r\n )\r\n }\r\n }\r\n\r\n if (process.env.NODE_ENV !== 'production') {\r\n if (immutableCheck) {\r\n /* PROD_START_REMOVE_UMD */\r\n let immutableOptions: ImmutableStateInvariantMiddlewareOptions = {}\r\n\r\n if (!isBoolean(immutableCheck)) {\r\n immutableOptions = immutableCheck\r\n }\r\n\r\n middlewareArray.unshift(\r\n createImmutableStateInvariantMiddleware(immutableOptions)\r\n )\r\n /* PROD_STOP_REMOVE_UMD */\r\n }\r\n\r\n if (serializableCheck) {\r\n let serializableOptions: SerializableStateInvariantMiddlewareOptions = {}\r\n\r\n if (!isBoolean(serializableCheck)) {\r\n serializableOptions = serializableCheck\r\n }\r\n\r\n middlewareArray.push(\r\n createSerializableStateInvariantMiddleware(serializableOptions)\r\n )\r\n }\r\n if (actionCreatorCheck) {\r\n let actionCreatorOptions: ActionCreatorInvariantMiddlewareOptions = {}\r\n\r\n if (!isBoolean(actionCreatorCheck)) {\r\n actionCreatorOptions = actionCreatorCheck\r\n }\r\n\r\n middlewareArray.unshift(\r\n createActionCreatorInvariantMiddleware(actionCreatorOptions)\r\n )\r\n }\r\n }\r\n\r\n return middlewareArray as any\r\n}\r\n", "import type { Middleware, StoreEnhancer } from 'redux'\r\nimport type { EnhancerArray, MiddlewareArray } from './utils'\r\n\r\n/**\r\n * return True if T is `any`, otherwise return False\r\n * taken from https://github.com/joonhocho/tsdef\r\n *\r\n * @internal\r\n */\r\nexport type IsAny =\r\n // test if we are going the left AND right path in the condition\r\n true | false extends (T extends never ? true : false) ? True : False\r\n\r\n/**\r\n * return True if T is `unknown`, otherwise return False\r\n * taken from https://github.com/joonhocho/tsdef\r\n *\r\n * @internal\r\n */\r\nexport type IsUnknown = unknown extends T\r\n ? IsAny\r\n : False\r\n\r\nexport type FallbackIfUnknown = IsUnknown\r\n\r\n/**\r\n * @internal\r\n */\r\nexport type IfMaybeUndefined = [undefined] extends [P]\r\n ? True\r\n : False\r\n\r\n/**\r\n * @internal\r\n */\r\nexport type IfVoid = [void] extends [P] ? True : False\r\n\r\n/**\r\n * @internal\r\n */\r\nexport type IsEmptyObj = T extends any\r\n ? keyof T extends never\r\n ? IsUnknown>>\r\n : False\r\n : never\r\n\r\n/**\r\n * returns True if TS version is above 3.5, False if below.\r\n * uses feature detection to detect TS version >= 3.5\r\n * * versions below 3.5 will return `{}` for unresolvable interference\r\n * * versions above will return `unknown`\r\n *\r\n * @internal\r\n */\r\nexport type AtLeastTS35 = [True, False][IsUnknown<\r\n ReturnType<() => T>,\r\n 0,\r\n 1\r\n>]\r\n\r\n/**\r\n * @internal\r\n */\r\nexport type IsUnknownOrNonInferrable = AtLeastTS35<\r\n IsUnknown,\r\n IsEmptyObj>\r\n>\r\n\r\n/**\r\n * Convert a Union type `(A|B)` to an intersection type `(A&B)`\r\n */\r\nexport type UnionToIntersection = (\r\n U extends any ? (k: U) => void : never\r\n) extends (k: infer I) => void\r\n ? I\r\n : never\r\n\r\n// Appears to have a convenient side effect of ignoring `never` even if that's not what you specified\r\nexport type ExcludeFromTuple = T extends [\r\n infer Head,\r\n ...infer Tail\r\n]\r\n ? ExcludeFromTuple\r\n : Acc\r\n\r\ntype ExtractDispatchFromMiddlewareTuple<\r\n MiddlewareTuple extends any[],\r\n Acc extends {}\r\n> = MiddlewareTuple extends [infer Head, ...infer Tail]\r\n ? ExtractDispatchFromMiddlewareTuple<\r\n Tail,\r\n Acc & (Head extends Middleware ? IsAny : {})\r\n >\r\n : Acc\r\n\r\nexport type ExtractDispatchExtensions = M extends MiddlewareArray<\r\n infer MiddlewareTuple\r\n>\r\n ? ExtractDispatchFromMiddlewareTuple\r\n : M extends ReadonlyArray\r\n ? ExtractDispatchFromMiddlewareTuple<[...M], {}>\r\n : never\r\n\r\ntype ExtractStoreExtensionsFromEnhancerTuple<\r\n EnhancerTuple extends any[],\r\n Acc extends {}\r\n> = EnhancerTuple extends [infer Head, ...infer Tail]\r\n ? ExtractStoreExtensionsFromEnhancerTuple<\r\n Tail,\r\n Acc & (Head extends StoreEnhancer ? IsAny : {})\r\n >\r\n : Acc\r\n\r\nexport type ExtractStoreExtensions = E extends EnhancerArray<\r\n infer EnhancerTuple\r\n>\r\n ? ExtractStoreExtensionsFromEnhancerTuple\r\n : E extends ReadonlyArray\r\n ? UnionToIntersection<\r\n E[number] extends StoreEnhancer\r\n ? Ext extends {}\r\n ? IsAny\r\n : {}\r\n : {}\r\n >\r\n : never\r\n\r\ntype ExtractStateExtensionsFromEnhancerTuple<\r\n EnhancerTuple extends any[],\r\n Acc extends {}\r\n> = EnhancerTuple extends [infer Head, ...infer Tail]\r\n ? ExtractStateExtensionsFromEnhancerTuple<\r\n Tail,\r\n Acc &\r\n (Head extends StoreEnhancer\r\n ? IsAny\r\n : {})\r\n >\r\n : Acc\r\n\r\nexport type ExtractStateExtensions = E extends EnhancerArray<\r\n infer EnhancerTuple\r\n>\r\n ? ExtractStateExtensionsFromEnhancerTuple\r\n : E extends ReadonlyArray\r\n ? UnionToIntersection<\r\n E[number] extends StoreEnhancer\r\n ? StateExt extends {}\r\n ? IsAny\r\n : {}\r\n : {}\r\n >\r\n : never\r\n\r\n/**\r\n * Helper type. Passes T out again, but boxes it in a way that it cannot\r\n * \"widen\" the type by accident if it is a generic that should be inferred\r\n * from elsewhere.\r\n *\r\n * @internal\r\n */\r\nexport type NoInfer = [T][T extends any ? 0 : never]\r\n\r\nexport type Omit = Pick>\r\n\r\nexport interface TypeGuard {\r\n (value: any): value is T\r\n}\r\n\r\nexport interface HasMatchFunction {\r\n match: TypeGuard\r\n}\r\n\r\nexport const hasMatchFunction = (\r\n v: Matcher\r\n): v is HasMatchFunction => {\r\n return v && typeof (v as HasMatchFunction).match === 'function'\r\n}\r\n\r\n/** @public */\r\nexport type Matcher = HasMatchFunction | TypeGuard\r\n\r\n/** @public */\r\nexport type ActionFromMatcher> = M extends Matcher<\r\n infer T\r\n>\r\n ? T\r\n : never\r\n\r\nexport type Id = { [K in keyof T]: T[K] } & {}\r\n", "import type { Action } from 'redux'\r\nimport type {\r\n IsUnknownOrNonInferrable,\r\n IfMaybeUndefined,\r\n IfVoid,\r\n IsAny,\r\n} from './tsHelpers'\r\nimport { hasMatchFunction } from './tsHelpers'\r\nimport isPlainObject from './isPlainObject'\r\n\r\n/**\r\n * An action with a string type and an associated payload. This is the\r\n * type of action returned by `createAction()` action creators.\r\n *\r\n * @template P The type of the action's payload.\r\n * @template T the type used for the action type.\r\n * @template M The type of the action's meta (optional)\r\n * @template E The type of the action's error (optional)\r\n *\r\n * @public\r\n */\r\nexport type PayloadAction<\r\n P = void,\r\n T extends string = string,\r\n M = never,\r\n E = never\r\n> = {\r\n payload: P\r\n type: T\r\n} & ([M] extends [never]\r\n ? {}\r\n : {\r\n meta: M\r\n }) &\r\n ([E] extends [never]\r\n ? {}\r\n : {\r\n error: E\r\n })\r\n\r\n/**\r\n * A \"prepare\" method to be used as the second parameter of `createAction`.\r\n * Takes any number of arguments and returns a Flux Standard Action without\r\n * type (will be added later) that *must* contain a payload (might be undefined).\r\n *\r\n * @public\r\n */\r\nexport type PrepareAction

=\r\n | ((...args: any[]) => { payload: P })\r\n | ((...args: any[]) => { payload: P; meta: any })\r\n | ((...args: any[]) => { payload: P; error: any })\r\n | ((...args: any[]) => { payload: P; meta: any; error: any })\r\n\r\n/**\r\n * Internal version of `ActionCreatorWithPreparedPayload`. Not to be used externally.\r\n *\r\n * @internal\r\n */\r\nexport type _ActionCreatorWithPreparedPayload<\r\n PA extends PrepareAction | void,\r\n T extends string = string\r\n> = PA extends PrepareAction\r\n ? ActionCreatorWithPreparedPayload<\r\n Parameters,\r\n P,\r\n T,\r\n ReturnType extends {\r\n error: infer E\r\n }\r\n ? E\r\n : never,\r\n ReturnType extends {\r\n meta: infer M\r\n }\r\n ? M\r\n : never\r\n >\r\n : void\r\n\r\n/**\r\n * Basic type for all action creators.\r\n *\r\n * @inheritdoc {redux#ActionCreator}\r\n */\r\nexport interface BaseActionCreator {\r\n type: T\r\n match: (action: Action) => action is PayloadAction\r\n}\r\n\r\n/**\r\n * An action creator that takes multiple arguments that are passed\r\n * to a `PrepareAction` method to create the final Action.\r\n * @typeParam Args arguments for the action creator function\r\n * @typeParam P `payload` type\r\n * @typeParam T `type` name\r\n * @typeParam E optional `error` type\r\n * @typeParam M optional `meta` type\r\n *\r\n * @inheritdoc {redux#ActionCreator}\r\n *\r\n * @public\r\n */\r\nexport interface ActionCreatorWithPreparedPayload<\r\n Args extends unknown[],\r\n P,\r\n T extends string = string,\r\n E = never,\r\n M = never\r\n> extends BaseActionCreator {\r\n /**\r\n * Calling this {@link redux#ActionCreator} with `Args` will return\r\n * an Action with a payload of type `P` and (depending on the `PrepareAction`\r\n * method used) a `meta`- and `error` property of types `M` and `E` respectively.\r\n */\r\n (...args: Args): PayloadAction\r\n}\r\n\r\n/**\r\n * An action creator of type `T` that takes an optional payload of type `P`.\r\n *\r\n * @inheritdoc {redux#ActionCreator}\r\n *\r\n * @public\r\n */\r\nexport interface ActionCreatorWithOptionalPayload\r\n extends BaseActionCreator {\r\n /**\r\n * Calling this {@link redux#ActionCreator} with an argument will\r\n * return a {@link PayloadAction} of type `T` with a payload of `P`.\r\n * Calling it without an argument will return a PayloadAction with a payload of `undefined`.\r\n */\r\n (payload?: P): PayloadAction\r\n}\r\n\r\n/**\r\n * An action creator of type `T` that takes no payload.\r\n *\r\n * @inheritdoc {redux#ActionCreator}\r\n *\r\n * @public\r\n */\r\nexport interface ActionCreatorWithoutPayload\r\n extends BaseActionCreator {\r\n /**\r\n * Calling this {@link redux#ActionCreator} will\r\n * return a {@link PayloadAction} of type `T` with a payload of `undefined`\r\n */\r\n (noArgument: void): PayloadAction\r\n}\r\n\r\n/**\r\n * An action creator of type `T` that requires a payload of type P.\r\n *\r\n * @inheritdoc {redux#ActionCreator}\r\n *\r\n * @public\r\n */\r\nexport interface ActionCreatorWithPayload\r\n extends BaseActionCreator {\r\n /**\r\n * Calling this {@link redux#ActionCreator} with an argument will\r\n * return a {@link PayloadAction} of type `T` with a payload of `P`\r\n */\r\n (payload: P): PayloadAction\r\n}\r\n\r\n/**\r\n * An action creator of type `T` whose `payload` type could not be inferred. Accepts everything as `payload`.\r\n *\r\n * @inheritdoc {redux#ActionCreator}\r\n *\r\n * @public\r\n */\r\nexport interface ActionCreatorWithNonInferrablePayload<\r\n T extends string = string\r\n> extends BaseActionCreator {\r\n /**\r\n * Calling this {@link redux#ActionCreator} with an argument will\r\n * return a {@link PayloadAction} of type `T` with a payload\r\n * of exactly the type of the argument.\r\n */\r\n (payload: PT): PayloadAction\r\n}\r\n\r\n/**\r\n * An action creator that produces actions with a `payload` attribute.\r\n *\r\n * @typeParam P the `payload` type\r\n * @typeParam T the `type` of the resulting action\r\n * @typeParam PA if the resulting action is preprocessed by a `prepare` method, the signature of said method.\r\n *\r\n * @public\r\n */\r\nexport type PayloadActionCreator<\r\n P = void,\r\n T extends string = string,\r\n PA extends PrepareAction

| void = void\r\n> = IfPrepareActionMethodProvided<\r\n PA,\r\n _ActionCreatorWithPreparedPayload,\r\n // else\r\n IsAny<\r\n P,\r\n ActionCreatorWithPayload,\r\n IsUnknownOrNonInferrable<\r\n P,\r\n ActionCreatorWithNonInferrablePayload,\r\n // else\r\n IfVoid<\r\n P,\r\n ActionCreatorWithoutPayload,\r\n // else\r\n IfMaybeUndefined<\r\n P,\r\n ActionCreatorWithOptionalPayload,\r\n // else\r\n ActionCreatorWithPayload\r\n >\r\n >\r\n >\r\n >\r\n>\r\n\r\n/**\r\n * A utility function to create an action creator for the given action type\r\n * string. The action creator accepts a single argument, which will be included\r\n * in the action object as a field called payload. The action creator function\r\n * will also have its toString() overridden so that it returns the action type,\r\n * allowing it to be used in reducer logic that is looking for that action type.\r\n *\r\n * @param type The action type to use for created actions.\r\n * @param prepare (optional) a method that takes any number of arguments and returns { payload } or { payload, meta }.\r\n * If this is given, the resulting action creator will pass its arguments to this method to calculate payload & meta.\r\n *\r\n * @public\r\n */\r\nexport function createAction

(\r\n type: T\r\n): PayloadActionCreator\r\n\r\n/**\r\n * A utility function to create an action creator for the given action type\r\n * string. The action creator accepts a single argument, which will be included\r\n * in the action object as a field called payload. The action creator function\r\n * will also have its toString() overridden so that it returns the action type,\r\n * allowing it to be used in reducer logic that is looking for that action type.\r\n *\r\n * @param type The action type to use for created actions.\r\n * @param prepare (optional) a method that takes any number of arguments and returns { payload } or { payload, meta }.\r\n * If this is given, the resulting action creator will pass its arguments to this method to calculate payload & meta.\r\n *\r\n * @public\r\n */\r\nexport function createAction<\r\n PA extends PrepareAction,\r\n T extends string = string\r\n>(\r\n type: T,\r\n prepareAction: PA\r\n): PayloadActionCreator['payload'], T, PA>\r\n\r\nexport function createAction(type: string, prepareAction?: Function): any {\r\n function actionCreator(...args: any[]) {\r\n if (prepareAction) {\r\n let prepared = prepareAction(...args)\r\n if (!prepared) {\r\n throw new Error('prepareAction did not return an object')\r\n }\r\n\r\n return {\r\n type,\r\n payload: prepared.payload,\r\n ...('meta' in prepared && { meta: prepared.meta }),\r\n ...('error' in prepared && { error: prepared.error }),\r\n }\r\n }\r\n return { type, payload: args[0] }\r\n }\r\n\r\n actionCreator.toString = () => `${type}`\r\n\r\n actionCreator.type = type\r\n\r\n actionCreator.match = (action: Action): action is PayloadAction =>\r\n action.type === type\r\n\r\n return actionCreator\r\n}\r\n\r\n/**\r\n * Returns true if value is a plain object with a `type` property.\r\n */\r\nexport function isAction(action: unknown): action is Action {\r\n return isPlainObject(action) && 'type' in action\r\n}\r\n\r\n/**\r\n * Returns true if value is an RTK-like action creator, with a static type property and match method.\r\n */\r\nexport function isActionCreator(\r\n action: unknown\r\n): action is BaseActionCreator & Function {\r\n return (\r\n typeof action === 'function' &&\r\n 'type' in action &&\r\n // hasMatchFunction only wants Matchers but I don't see the point in rewriting it\r\n hasMatchFunction(action as any)\r\n )\r\n}\r\n\r\n/**\r\n * Returns true if value is an action with a string type and valid Flux Standard Action keys.\r\n */\r\nexport function isFSA(action: unknown): action is {\r\n type: string\r\n payload?: unknown\r\n error?: unknown\r\n meta?: unknown\r\n} {\r\n return (\r\n isAction(action) &&\r\n typeof action.type === 'string' &&\r\n Object.keys(action).every(isValidKey)\r\n )\r\n}\r\n\r\nfunction isValidKey(key: string) {\r\n return ['type', 'payload', 'error', 'meta'].indexOf(key) > -1\r\n}\r\n\r\n/**\r\n * Returns the action type of the actions created by the passed\r\n * `createAction()`-generated action creator (arbitrary action creators\r\n * are not supported).\r\n *\r\n * @param action The action creator whose action type to get.\r\n * @returns The action type used by the action creator.\r\n *\r\n * @public\r\n */\r\nexport function getType(\r\n actionCreator: PayloadActionCreator\r\n): T {\r\n return `${actionCreator}` as T\r\n}\r\n\r\n// helper types for more readable typings\r\n\r\ntype IfPrepareActionMethodProvided<\r\n PA extends PrepareAction | void,\r\n True,\r\n False\r\n> = PA extends (...args: any[]) => any ? True : False\r\n", "import type { Middleware } from 'redux'\r\nimport { isActionCreator as isRTKAction } from './createAction'\r\n\r\nexport interface ActionCreatorInvariantMiddlewareOptions {\r\n /**\r\n * The function to identify whether a value is an action creator.\r\n * The default checks for a function with a static type property and match method.\r\n */\r\n isActionCreator?: (action: unknown) => action is Function & { type?: unknown }\r\n}\r\n\r\nexport function getMessage(type?: unknown) {\r\n const splitType = type ? `${type}`.split('/') : []\r\n const actionName = splitType[splitType.length - 1] || 'actionCreator'\r\n return `Detected an action creator with type \"${\r\n type || 'unknown'\r\n }\" being dispatched. \r\nMake sure you're calling the action creator before dispatching, i.e. \\`dispatch(${actionName}())\\` instead of \\`dispatch(${actionName})\\`. This is necessary even if the action has no payload.`\r\n}\r\n\r\nexport function createActionCreatorInvariantMiddleware(\r\n options: ActionCreatorInvariantMiddlewareOptions = {}\r\n): Middleware {\r\n if (process.env.NODE_ENV === 'production') {\r\n return () => (next) => (action) => next(action)\r\n }\r\n const { isActionCreator = isRTKAction } = options\r\n return () => (next) => (action) => {\r\n if (isActionCreator(action)) {\r\n console.warn(getMessage(action.type))\r\n }\r\n return next(action)\r\n }\r\n}\r\n", "import createNextState, { isDraftable } from 'immer'\r\nimport type { Middleware, StoreEnhancer } from 'redux'\r\n\r\nexport function getTimeMeasureUtils(maxDelay: number, fnName: string) {\r\n let elapsed = 0\r\n return {\r\n measureTime(fn: () => T): T {\r\n const started = Date.now()\r\n try {\r\n return fn()\r\n } finally {\r\n const finished = Date.now()\r\n elapsed += finished - started\r\n }\r\n },\r\n warnIfExceeded() {\r\n if (elapsed > maxDelay) {\r\n console.warn(`${fnName} took ${elapsed}ms, which is more than the warning threshold of ${maxDelay}ms. \r\nIf your state or actions are very large, you may want to disable the middleware as it might cause too much of a slowdown in development mode. See https://redux-toolkit.js.org/api/getDefaultMiddleware for instructions.\r\nIt is disabled in production builds, so you don't need to worry about that.`)\r\n }\r\n },\r\n }\r\n}\r\n\r\nexport function delay(ms: number) {\r\n return new Promise((resolve) => setTimeout(resolve, ms))\r\n}\r\n\r\n/**\r\n * @public\r\n */\r\nexport class MiddlewareArray<\r\n Middlewares extends Middleware[]\r\n> extends Array {\r\n constructor(...items: Middlewares)\r\n constructor(...args: any[]) {\r\n super(...args)\r\n Object.setPrototypeOf(this, MiddlewareArray.prototype)\r\n }\r\n\r\n static get [Symbol.species]() {\r\n return MiddlewareArray as any\r\n }\r\n\r\n concat>>(\r\n items: AdditionalMiddlewares\r\n ): MiddlewareArray<[...Middlewares, ...AdditionalMiddlewares]>\r\n\r\n concat>>(\r\n ...items: AdditionalMiddlewares\r\n ): MiddlewareArray<[...Middlewares, ...AdditionalMiddlewares]>\r\n concat(...arr: any[]) {\r\n return super.concat.apply(this, arr)\r\n }\r\n\r\n prepend>>(\r\n items: AdditionalMiddlewares\r\n ): MiddlewareArray<[...AdditionalMiddlewares, ...Middlewares]>\r\n\r\n prepend>>(\r\n ...items: AdditionalMiddlewares\r\n ): MiddlewareArray<[...AdditionalMiddlewares, ...Middlewares]>\r\n\r\n prepend(...arr: any[]) {\r\n if (arr.length === 1 && Array.isArray(arr[0])) {\r\n return new MiddlewareArray(...arr[0].concat(this))\r\n }\r\n return new MiddlewareArray(...arr.concat(this))\r\n }\r\n}\r\n\r\n/**\r\n * @public\r\n */\r\nexport class EnhancerArray<\r\n Enhancers extends StoreEnhancer[]\r\n> extends Array {\r\n constructor(...items: Enhancers)\r\n constructor(...args: any[]) {\r\n super(...args)\r\n Object.setPrototypeOf(this, EnhancerArray.prototype)\r\n }\r\n\r\n static get [Symbol.species]() {\r\n return EnhancerArray as any\r\n }\r\n\r\n concat>>(\r\n items: AdditionalEnhancers\r\n ): EnhancerArray<[...Enhancers, ...AdditionalEnhancers]>\r\n\r\n concat>>(\r\n ...items: AdditionalEnhancers\r\n ): EnhancerArray<[...Enhancers, ...AdditionalEnhancers]>\r\n concat(...arr: any[]) {\r\n return super.concat.apply(this, arr)\r\n }\r\n\r\n prepend>>(\r\n items: AdditionalEnhancers\r\n ): EnhancerArray<[...AdditionalEnhancers, ...Enhancers]>\r\n\r\n prepend>>(\r\n ...items: AdditionalEnhancers\r\n ): EnhancerArray<[...AdditionalEnhancers, ...Enhancers]>\r\n\r\n prepend(...arr: any[]) {\r\n if (arr.length === 1 && Array.isArray(arr[0])) {\r\n return new EnhancerArray(...arr[0].concat(this))\r\n }\r\n return new EnhancerArray(...arr.concat(this))\r\n }\r\n}\r\n\r\nexport function freezeDraftable(val: T) {\r\n return isDraftable(val) ? createNextState(val, () => {}) : val\r\n}\r\n", "import type { Middleware } from 'redux'\r\nimport { getTimeMeasureUtils } from './utils'\r\n\r\ntype EntryProcessor = (key: string, value: any) => any\r\n\r\nconst isProduction: boolean = process.env.NODE_ENV === 'production'\r\nconst prefix: string = 'Invariant failed'\r\n\r\n// Throw an error if the condition fails\r\n// Strip out error messages for production\r\n// > Not providing an inline default argument for message as the result is smaller\r\nfunction invariant(condition: any, message?: string) {\r\n if (condition) {\r\n return\r\n }\r\n // Condition not passed\r\n\r\n // In production we strip the message but still throw\r\n if (isProduction) {\r\n throw new Error(prefix)\r\n }\r\n\r\n // When not in production we allow the message to pass through\r\n // *This block will be removed in production builds*\r\n throw new Error(`${prefix}: ${message || ''}`)\r\n}\r\n\r\nfunction stringify(\r\n obj: any,\r\n serializer?: EntryProcessor,\r\n indent?: string | number,\r\n decycler?: EntryProcessor\r\n): string {\r\n return JSON.stringify(obj, getSerialize(serializer, decycler), indent)\r\n}\r\n\r\nfunction getSerialize(\r\n serializer?: EntryProcessor,\r\n decycler?: EntryProcessor\r\n): EntryProcessor {\r\n let stack: any[] = [],\r\n keys: any[] = []\r\n\r\n if (!decycler)\r\n decycler = function (_: string, value: any) {\r\n if (stack[0] === value) return '[Circular ~]'\r\n return (\r\n '[Circular ~.' + keys.slice(0, stack.indexOf(value)).join('.') + ']'\r\n )\r\n }\r\n\r\n return function (this: any, key: string, value: any) {\r\n if (stack.length > 0) {\r\n var thisPos = stack.indexOf(this)\r\n ~thisPos ? stack.splice(thisPos + 1) : stack.push(this)\r\n ~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key)\r\n if (~stack.indexOf(value)) value = decycler!.call(this, key, value)\r\n } else stack.push(value)\r\n\r\n return serializer == null ? value : serializer.call(this, key, value)\r\n }\r\n}\r\n\r\n/**\r\n * The default `isImmutable` function.\r\n *\r\n * @public\r\n */\r\nexport function isImmutableDefault(value: unknown): boolean {\r\n return typeof value !== 'object' || value == null || Object.isFrozen(value)\r\n}\r\n\r\nexport function trackForMutations(\r\n isImmutable: IsImmutableFunc,\r\n ignorePaths: IgnorePaths | undefined,\r\n obj: any\r\n) {\r\n const trackedProperties = trackProperties(isImmutable, ignorePaths, obj)\r\n return {\r\n detectMutations() {\r\n return detectMutations(isImmutable, ignorePaths, trackedProperties, obj)\r\n },\r\n }\r\n}\r\n\r\ninterface TrackedProperty {\r\n value: any\r\n children: Record\r\n}\r\n\r\nfunction trackProperties(\r\n isImmutable: IsImmutableFunc,\r\n ignorePaths: IgnorePaths = [],\r\n obj: Record,\r\n path: string = '',\r\n checkedObjects: Set> = new Set()\r\n) {\r\n const tracked: Partial = { value: obj }\r\n\r\n if (!isImmutable(obj) && !checkedObjects.has(obj)) {\r\n checkedObjects.add(obj);\r\n tracked.children = {}\r\n\r\n for (const key in obj) {\r\n const childPath = path ? path + '.' + key : key\r\n if (ignorePaths.length && ignorePaths.indexOf(childPath) !== -1) {\r\n continue\r\n }\r\n\r\n tracked.children[key] = trackProperties(\r\n isImmutable,\r\n ignorePaths,\r\n obj[key],\r\n childPath\r\n )\r\n }\r\n }\r\n return tracked as TrackedProperty\r\n}\r\n\r\ntype IgnorePaths = readonly (string | RegExp)[]\r\n\r\nfunction detectMutations(\r\n isImmutable: IsImmutableFunc,\r\n ignoredPaths: IgnorePaths = [],\r\n trackedProperty: TrackedProperty,\r\n obj: any,\r\n sameParentRef: boolean = false,\r\n path: string = ''\r\n): { wasMutated: boolean; path?: string } {\r\n const prevObj = trackedProperty ? trackedProperty.value : undefined\r\n\r\n const sameRef = prevObj === obj\r\n\r\n if (sameParentRef && !sameRef && !Number.isNaN(obj)) {\r\n return { wasMutated: true, path }\r\n }\r\n\r\n if (isImmutable(prevObj) || isImmutable(obj)) {\r\n return { wasMutated: false }\r\n }\r\n\r\n // Gather all keys from prev (tracked) and after objs\r\n const keysToDetect: Record = {}\r\n for (let key in trackedProperty.children) {\r\n keysToDetect[key] = true\r\n }\r\n for (let key in obj) {\r\n keysToDetect[key] = true\r\n }\r\n\r\n const hasIgnoredPaths = ignoredPaths.length > 0\r\n\r\n for (let key in keysToDetect) {\r\n const nestedPath = path ? path + '.' + key : key\r\n\r\n if (hasIgnoredPaths) {\r\n const hasMatches = ignoredPaths.some((ignored) => {\r\n if (ignored instanceof RegExp) {\r\n return ignored.test(nestedPath)\r\n }\r\n return nestedPath === ignored\r\n })\r\n if (hasMatches) {\r\n continue\r\n }\r\n }\r\n\r\n const result = detectMutations(\r\n isImmutable,\r\n ignoredPaths,\r\n trackedProperty.children[key],\r\n obj[key],\r\n sameRef,\r\n nestedPath\r\n )\r\n\r\n if (result.wasMutated) {\r\n return result\r\n }\r\n }\r\n return { wasMutated: false }\r\n}\r\n\r\ntype IsImmutableFunc = (value: any) => boolean\r\n\r\n/**\r\n * Options for `createImmutableStateInvariantMiddleware()`.\r\n *\r\n * @public\r\n */\r\nexport interface ImmutableStateInvariantMiddlewareOptions {\r\n /**\r\n Callback function to check if a value is considered to be immutable.\r\n This function is applied recursively to every value contained in the state.\r\n The default implementation will return true for primitive types \r\n (like numbers, strings, booleans, null and undefined).\r\n */\r\n isImmutable?: IsImmutableFunc\r\n /** \r\n An array of dot-separated path strings that match named nodes from \r\n the root state to ignore when checking for immutability.\r\n Defaults to undefined\r\n */\r\n ignoredPaths?: IgnorePaths\r\n /** Print a warning if checks take longer than N ms. Default: 32ms */\r\n warnAfter?: number\r\n // @deprecated. Use ignoredPaths\r\n ignore?: string[]\r\n}\r\n\r\n/**\r\n * Creates a middleware that checks whether any state was mutated in between\r\n * dispatches or during a dispatch. If any mutations are detected, an error is\r\n * thrown.\r\n *\r\n * @param options Middleware options.\r\n *\r\n * @public\r\n */\r\nexport function createImmutableStateInvariantMiddleware(\r\n options: ImmutableStateInvariantMiddlewareOptions = {}\r\n): Middleware {\r\n if (process.env.NODE_ENV === 'production') {\r\n return () => (next) => (action) => next(action)\r\n }\r\n\r\n let {\r\n isImmutable = isImmutableDefault,\r\n ignoredPaths,\r\n warnAfter = 32,\r\n ignore,\r\n } = options\r\n\r\n // Alias ignore->ignoredPaths, but prefer ignoredPaths if present\r\n ignoredPaths = ignoredPaths || ignore\r\n\r\n const track = trackForMutations.bind(null, isImmutable, ignoredPaths)\r\n\r\n return ({ getState }) => {\r\n let state = getState()\r\n let tracker = track(state)\r\n\r\n let result\r\n return (next) => (action) => {\r\n const measureUtils = getTimeMeasureUtils(\r\n warnAfter,\r\n 'ImmutableStateInvariantMiddleware'\r\n )\r\n\r\n measureUtils.measureTime(() => {\r\n state = getState()\r\n\r\n result = tracker.detectMutations()\r\n // Track before potentially not meeting the invariant\r\n tracker = track(state)\r\n\r\n invariant(\r\n !result.wasMutated,\r\n `A state mutation was detected between dispatches, in the path '${\r\n result.path || ''\r\n }'. This may cause incorrect behavior. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`\r\n )\r\n })\r\n\r\n const dispatchedAction = next(action)\r\n\r\n measureUtils.measureTime(() => {\r\n state = getState()\r\n\r\n result = tracker.detectMutations()\r\n // Track before potentially not meeting the invariant\r\n tracker = track(state)\r\n\r\n result.wasMutated &&\r\n invariant(\r\n !result.wasMutated,\r\n `A state mutation was detected inside a dispatch, in the path: ${\r\n result.path || ''\r\n }. Take a look at the reducer(s) handling the action ${stringify(\r\n action\r\n )}. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`\r\n )\r\n })\r\n\r\n measureUtils.warnIfExceeded()\r\n\r\n return dispatchedAction\r\n }\r\n }\r\n}\r\n", "import isPlainObject from './isPlainObject'\r\nimport type { Middleware } from 'redux'\r\nimport { getTimeMeasureUtils } from './utils'\r\n\r\n/**\r\n * Returns true if the passed value is \"plain\", i.e. a value that is either\r\n * directly JSON-serializable (boolean, number, string, array, plain object)\r\n * or `undefined`.\r\n *\r\n * @param val The value to check.\r\n *\r\n * @public\r\n */\r\nexport function isPlain(val: any) {\r\n const type = typeof val\r\n return (\r\n val == null ||\r\n type === 'string' ||\r\n type === 'boolean' ||\r\n type === 'number' ||\r\n Array.isArray(val) ||\r\n isPlainObject(val)\r\n )\r\n}\r\n\r\ninterface NonSerializableValue {\r\n keyPath: string\r\n value: unknown\r\n}\r\n\r\ntype IgnorePaths = readonly (string | RegExp)[]\r\n\r\n/**\r\n * @public\r\n */\r\nexport function findNonSerializableValue(\r\n value: unknown,\r\n path: string = '',\r\n isSerializable: (value: unknown) => boolean = isPlain,\r\n getEntries?: (value: unknown) => [string, any][],\r\n ignoredPaths: IgnorePaths = [],\r\n cache?: WeakSet\r\n): NonSerializableValue | false {\r\n let foundNestedSerializable: NonSerializableValue | false\r\n\r\n if (!isSerializable(value)) {\r\n return {\r\n keyPath: path || '',\r\n value: value,\r\n }\r\n }\r\n\r\n if (typeof value !== 'object' || value === null) {\r\n return false\r\n }\r\n\r\n if (cache?.has(value)) return false\r\n\r\n const entries = getEntries != null ? getEntries(value) : Object.entries(value)\r\n\r\n const hasIgnoredPaths = ignoredPaths.length > 0\r\n\r\n for (const [key, nestedValue] of entries) {\r\n const nestedPath = path ? path + '.' + key : key\r\n\r\n if (hasIgnoredPaths) {\r\n const hasMatches = ignoredPaths.some((ignored) => {\r\n if (ignored instanceof RegExp) {\r\n return ignored.test(nestedPath)\r\n }\r\n return nestedPath === ignored\r\n })\r\n if (hasMatches) {\r\n continue\r\n }\r\n }\r\n\r\n if (!isSerializable(nestedValue)) {\r\n return {\r\n keyPath: nestedPath,\r\n value: nestedValue,\r\n }\r\n }\r\n\r\n if (typeof nestedValue === 'object') {\r\n foundNestedSerializable = findNonSerializableValue(\r\n nestedValue,\r\n nestedPath,\r\n isSerializable,\r\n getEntries,\r\n ignoredPaths,\r\n cache\r\n )\r\n\r\n if (foundNestedSerializable) {\r\n return foundNestedSerializable\r\n }\r\n }\r\n }\r\n\r\n if (cache && isNestedFrozen(value)) cache.add(value)\r\n\r\n return false\r\n}\r\n\r\nexport function isNestedFrozen(value: object) {\r\n if (!Object.isFrozen(value)) return false\r\n\r\n for (const nestedValue of Object.values(value)) {\r\n if (typeof nestedValue !== 'object' || nestedValue === null) continue\r\n\r\n if (!isNestedFrozen(nestedValue)) return false\r\n }\r\n\r\n return true\r\n}\r\n\r\n/**\r\n * Options for `createSerializableStateInvariantMiddleware()`.\r\n *\r\n * @public\r\n */\r\nexport interface SerializableStateInvariantMiddlewareOptions {\r\n /**\r\n * The function to check if a value is considered serializable. This\r\n * function is applied recursively to every value contained in the\r\n * state. Defaults to `isPlain()`.\r\n */\r\n isSerializable?: (value: any) => boolean\r\n /**\r\n * The function that will be used to retrieve entries from each\r\n * value. If unspecified, `Object.entries` will be used. Defaults\r\n * to `undefined`.\r\n */\r\n getEntries?: (value: any) => [string, any][]\r\n\r\n /**\r\n * An array of action types to ignore when checking for serializability.\r\n * Defaults to []\r\n */\r\n ignoredActions?: string[]\r\n\r\n /**\r\n * An array of dot-separated path strings or regular expressions to ignore\r\n * when checking for serializability, Defaults to\r\n * ['meta.arg', 'meta.baseQueryMeta']\r\n */\r\n ignoredActionPaths?: (string | RegExp)[]\r\n\r\n /**\r\n * An array of dot-separated path strings or regular expressions to ignore\r\n * when checking for serializability, Defaults to []\r\n */\r\n ignoredPaths?: (string | RegExp)[]\r\n /**\r\n * Execution time warning threshold. If the middleware takes longer\r\n * than `warnAfter` ms, a warning will be displayed in the console.\r\n * Defaults to 32ms.\r\n */\r\n warnAfter?: number\r\n\r\n /**\r\n * Opt out of checking state. When set to `true`, other state-related params will be ignored.\r\n */\r\n ignoreState?: boolean\r\n\r\n /**\r\n * Opt out of checking actions. When set to `true`, other action-related params will be ignored.\r\n */\r\n ignoreActions?: boolean\r\n\r\n /**\r\n * Opt out of caching the results. The cache uses a WeakSet and speeds up repeated checking processes.\r\n * The cache is automatically disabled if no browser support for WeakSet is present.\r\n */\r\n disableCache?: boolean\r\n}\r\n\r\n/**\r\n * Creates a middleware that, after every state change, checks if the new\r\n * state is serializable. If a non-serializable value is found within the\r\n * state, an error is printed to the console.\r\n *\r\n * @param options Middleware options.\r\n *\r\n * @public\r\n */\r\nexport function createSerializableStateInvariantMiddleware(\r\n options: SerializableStateInvariantMiddlewareOptions = {}\r\n): Middleware {\r\n if (process.env.NODE_ENV === 'production') {\r\n return () => (next) => (action) => next(action)\r\n }\r\n const {\r\n isSerializable = isPlain,\r\n getEntries,\r\n ignoredActions = [],\r\n ignoredActionPaths = ['meta.arg', 'meta.baseQueryMeta'],\r\n ignoredPaths = [],\r\n warnAfter = 32,\r\n ignoreState = false,\r\n ignoreActions = false,\r\n disableCache = false,\r\n } = options\r\n\r\n const cache: WeakSet | undefined =\r\n !disableCache && WeakSet ? new WeakSet() : undefined\r\n\r\n return (storeAPI) => (next) => (action) => {\r\n const result = next(action)\r\n\r\n const measureUtils = getTimeMeasureUtils(\r\n warnAfter,\r\n 'SerializableStateInvariantMiddleware'\r\n )\r\n\r\n if (\r\n !ignoreActions &&\r\n !(ignoredActions.length && ignoredActions.indexOf(action.type) !== -1)\r\n ) {\r\n measureUtils.measureTime(() => {\r\n const foundActionNonSerializableValue = findNonSerializableValue(\r\n action,\r\n '',\r\n isSerializable,\r\n getEntries,\r\n ignoredActionPaths,\r\n cache\r\n )\r\n\r\n if (foundActionNonSerializableValue) {\r\n const { keyPath, value } = foundActionNonSerializableValue\r\n\r\n console.error(\r\n `A non-serializable value was detected in an action, in the path: \\`${keyPath}\\`. Value:`,\r\n value,\r\n '\\nTake a look at the logic that dispatched this action: ',\r\n action,\r\n '\\n(See https://redux.js.org/faq/actions#why-should-type-be-a-string-or-at-least-serializable-why-should-my-action-types-be-constants)',\r\n '\\n(To allow non-serializable values see: https://redux-toolkit.js.org/usage/usage-guide#working-with-non-serializable-data)'\r\n )\r\n }\r\n })\r\n }\r\n\r\n if (!ignoreState) {\r\n measureUtils.measureTime(() => {\r\n const state = storeAPI.getState()\r\n\r\n const foundStateNonSerializableValue = findNonSerializableValue(\r\n state,\r\n '',\r\n isSerializable,\r\n getEntries,\r\n ignoredPaths,\r\n cache\r\n )\r\n\r\n if (foundStateNonSerializableValue) {\r\n const { keyPath, value } = foundStateNonSerializableValue\r\n\r\n console.error(\r\n `A non-serializable value was detected in the state, in the path: \\`${keyPath}\\`. Value:`,\r\n value,\r\n `\r\nTake a look at the reducer(s) handling this action type: ${action.type}.\r\n(See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)`\r\n )\r\n }\r\n })\r\n\r\n measureUtils.warnIfExceeded()\r\n }\r\n\r\n return result\r\n }\r\n}\r\n", "import type { Draft } from 'immer'\r\nimport createNextState, { isDraft, isDraftable } from 'immer'\r\nimport type { AnyAction, Action, Reducer } from 'redux'\r\nimport type { ActionReducerMapBuilder } from './mapBuilders'\r\nimport { executeReducerBuilderCallback } from './mapBuilders'\r\nimport type { NoInfer } from './tsHelpers'\r\nimport { freezeDraftable } from './utils'\r\n\r\n/**\r\n * Defines a mapping from action types to corresponding action object shapes.\r\n *\r\n * @deprecated This should not be used manually - it is only used for internal\r\n * inference purposes and should not have any further value.\r\n * It might be removed in the future.\r\n * @public\r\n */\r\nexport type Actions = Record\r\n\r\n/**\r\n * @deprecated use `TypeGuard` instead\r\n */\r\nexport interface ActionMatcher {\r\n (action: AnyAction): action is A\r\n}\r\n\r\nexport type ActionMatcherDescription = {\r\n matcher: ActionMatcher\r\n reducer: CaseReducer>\r\n}\r\n\r\nexport type ReadonlyActionMatcherDescriptionCollection = ReadonlyArray<\r\n ActionMatcherDescription\r\n>\r\n\r\nexport type ActionMatcherDescriptionCollection = Array<\r\n ActionMatcherDescription\r\n>\r\n\r\n/**\r\n * A *case reducer* is a reducer function for a specific action type. Case\r\n * reducers can be composed to full reducers using `createReducer()`.\r\n *\r\n * Unlike a normal Redux reducer, a case reducer is never called with an\r\n * `undefined` state to determine the initial state. Instead, the initial\r\n * state is explicitly specified as an argument to `createReducer()`.\r\n *\r\n * In addition, a case reducer can choose to mutate the passed-in `state`\r\n * value directly instead of returning a new state. This does not actually\r\n * cause the store state to be mutated directly; instead, thanks to\r\n * [immer](https://github.com/mweststrate/immer), the mutations are\r\n * translated to copy operations that result in a new state.\r\n *\r\n * @public\r\n */\r\nexport type CaseReducer = (\r\n state: Draft,\r\n action: A\r\n) => NoInfer | void | Draft>\r\n\r\n/**\r\n * A mapping from action types to case reducers for `createReducer()`.\r\n *\r\n * @deprecated This should not be used manually - it is only used\r\n * for internal inference purposes and using it manually\r\n * would lead to type erasure.\r\n * It might be removed in the future.\r\n * @public\r\n */\r\nexport type CaseReducers = {\r\n [T in keyof AS]: AS[T] extends Action ? CaseReducer : void\r\n}\r\n\r\nexport type NotFunction = T extends Function ? never : T\r\n\r\nfunction isStateFunction(x: unknown): x is () => S {\r\n return typeof x === 'function'\r\n}\r\n\r\nexport type ReducerWithInitialState> = Reducer & {\r\n getInitialState: () => S\r\n}\r\n\r\nlet hasWarnedAboutObjectNotation = false\r\n\r\n/**\r\n * A utility function that allows defining a reducer as a mapping from action\r\n * type to *case reducer* functions that handle these action types. The\r\n * reducer's initial state is passed as the first argument.\r\n *\r\n * @remarks\r\n * The body of every case reducer is implicitly wrapped with a call to\r\n * `produce()` from the [immer](https://github.com/mweststrate/immer) library.\r\n * This means that rather than returning a new state object, you can also\r\n * mutate the passed-in state object directly; these mutations will then be\r\n * automatically and efficiently translated into copies, giving you both\r\n * convenience and immutability.\r\n *\r\n * @overloadSummary\r\n * This overload accepts a callback function that receives a `builder` object as its argument.\r\n * That builder provides `addCase`, `addMatcher` and `addDefaultCase` functions that may be\r\n * called to define what actions this reducer will handle.\r\n *\r\n * @param initialState - `State | (() => State)`: The initial state that should be used when the reducer is called the first time. This may also be a \"lazy initializer\" function, which should return an initial state value when called. This will be used whenever the reducer is called with `undefined` as its state value, and is primarily useful for cases like reading initial state from `localStorage`.\r\n * @param builderCallback - `(builder: Builder) => void` A callback that receives a *builder* object to define\r\n * case reducers via calls to `builder.addCase(actionCreatorOrType, reducer)`.\r\n * @example\r\n```ts\r\nimport {\r\n createAction,\r\n createReducer,\r\n AnyAction,\r\n PayloadAction,\r\n} from \"@reduxjs/toolkit\";\r\n\r\nconst increment = createAction(\"increment\");\r\nconst decrement = createAction(\"decrement\");\r\n\r\nfunction isActionWithNumberPayload(\r\n action: AnyAction\r\n): action is PayloadAction {\r\n return typeof action.payload === \"number\";\r\n}\r\n\r\nconst reducer = createReducer(\r\n {\r\n counter: 0,\r\n sumOfNumberPayloads: 0,\r\n unhandledActions: 0,\r\n },\r\n (builder) => {\r\n builder\r\n .addCase(increment, (state, action) => {\r\n // action is inferred correctly here\r\n state.counter += action.payload;\r\n })\r\n // You can chain calls, or have separate `builder.addCase()` lines each time\r\n .addCase(decrement, (state, action) => {\r\n state.counter -= action.payload;\r\n })\r\n // You can apply a \"matcher function\" to incoming actions\r\n .addMatcher(isActionWithNumberPayload, (state, action) => {})\r\n // and provide a default case if no other handlers matched\r\n .addDefaultCase((state, action) => {});\r\n }\r\n);\r\n```\r\n * @public\r\n */\r\nexport function createReducer>(\r\n initialState: S | (() => S),\r\n builderCallback: (builder: ActionReducerMapBuilder) => void\r\n): ReducerWithInitialState\r\n\r\n/**\r\n * A utility function that allows defining a reducer as a mapping from action\r\n * type to *case reducer* functions that handle these action types. The\r\n * reducer's initial state is passed as the first argument.\r\n *\r\n * The body of every case reducer is implicitly wrapped with a call to\r\n * `produce()` from the [immer](https://github.com/mweststrate/immer) library.\r\n * This means that rather than returning a new state object, you can also\r\n * mutate the passed-in state object directly; these mutations will then be\r\n * automatically and efficiently translated into copies, giving you both\r\n * convenience and immutability.\r\n * \r\n * @overloadSummary\r\n * This overload accepts an object where the keys are string action types, and the values\r\n * are case reducer functions to handle those action types.\r\n *\r\n * @param initialState - `State | (() => State)`: The initial state that should be used when the reducer is called the first time. This may also be a \"lazy initializer\" function, which should return an initial state value when called. This will be used whenever the reducer is called with `undefined` as its state value, and is primarily useful for cases like reading initial state from `localStorage`.\r\n * @param actionsMap - An object mapping from action types to _case reducers_, each of which handles one specific action type.\r\n * @param actionMatchers - An array of matcher definitions in the form `{matcher, reducer}`.\r\n * All matching reducers will be executed in order, independently if a case reducer matched or not.\r\n * @param defaultCaseReducer - A \"default case\" reducer that is executed if no case reducer and no matcher\r\n * reducer was executed for this action.\r\n *\r\n * @example\r\n```js\r\nconst counterReducer = createReducer(0, {\r\n increment: (state, action) => state + action.payload,\r\n decrement: (state, action) => state - action.payload\r\n})\r\n\r\n// Alternately, use a \"lazy initializer\" to provide the initial state\r\n// (works with either form of createReducer)\r\nconst initialState = () => 0\r\nconst counterReducer = createReducer(initialState, {\r\n increment: (state, action) => state + action.payload,\r\n decrement: (state, action) => state - action.payload\r\n})\r\n```\r\n \r\n * Action creators that were generated using [`createAction`](./createAction) may be used directly as the keys here, using computed property syntax:\r\n\r\n```js\r\nconst increment = createAction('increment')\r\nconst decrement = createAction('decrement')\r\n\r\nconst counterReducer = createReducer(0, {\r\n [increment]: (state, action) => state + action.payload,\r\n [decrement.type]: (state, action) => state - action.payload\r\n})\r\n```\r\n * @public\r\n */\r\nexport function createReducer<\r\n S extends NotFunction,\r\n CR extends CaseReducers = CaseReducers\r\n>(\r\n initialState: S | (() => S),\r\n actionsMap: CR,\r\n actionMatchers?: ActionMatcherDescriptionCollection,\r\n defaultCaseReducer?: CaseReducer\r\n): ReducerWithInitialState\r\n\r\nexport function createReducer>(\r\n initialState: S | (() => S),\r\n mapOrBuilderCallback:\r\n | CaseReducers\r\n | ((builder: ActionReducerMapBuilder) => void),\r\n actionMatchers: ReadonlyActionMatcherDescriptionCollection = [],\r\n defaultCaseReducer?: CaseReducer\r\n): ReducerWithInitialState {\r\n if (process.env.NODE_ENV !== 'production') {\r\n if (typeof mapOrBuilderCallback === 'object') {\r\n if (!hasWarnedAboutObjectNotation) {\r\n hasWarnedAboutObjectNotation = true\r\n console.warn(\r\n \"The object notation for `createReducer` is deprecated, and will be removed in RTK 2.0. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createReducer\"\r\n )\r\n }\r\n }\r\n }\r\n\r\n let [actionsMap, finalActionMatchers, finalDefaultCaseReducer] =\r\n typeof mapOrBuilderCallback === 'function'\r\n ? executeReducerBuilderCallback(mapOrBuilderCallback)\r\n : [mapOrBuilderCallback, actionMatchers, defaultCaseReducer]\r\n\r\n // Ensure the initial state gets frozen either way (if draftable)\r\n let getInitialState: () => S\r\n if (isStateFunction(initialState)) {\r\n getInitialState = () => freezeDraftable(initialState())\r\n } else {\r\n const frozenInitialState = freezeDraftable(initialState)\r\n getInitialState = () => frozenInitialState\r\n }\r\n\r\n function reducer(state = getInitialState(), action: any): S {\r\n let caseReducers = [\r\n actionsMap[action.type],\r\n ...finalActionMatchers\r\n .filter(({ matcher }) => matcher(action))\r\n .map(({ reducer }) => reducer),\r\n ]\r\n if (caseReducers.filter((cr) => !!cr).length === 0) {\r\n caseReducers = [finalDefaultCaseReducer]\r\n }\r\n\r\n return caseReducers.reduce((previousState, caseReducer): S => {\r\n if (caseReducer) {\r\n if (isDraft(previousState)) {\r\n // If it's already a draft, we must already be inside a `createNextState` call,\r\n // likely because this is being wrapped in `createReducer`, `createSlice`, or nested\r\n // inside an existing draft. It's safe to just pass the draft to the mutator.\r\n const draft = previousState as Draft // We can assume this is already a draft\r\n const result = caseReducer(draft, action)\r\n\r\n if (result === undefined) {\r\n return previousState\r\n }\r\n\r\n return result as S\r\n } else if (!isDraftable(previousState)) {\r\n // If state is not draftable (ex: a primitive, such as 0), we want to directly\r\n // return the caseReducer func and not wrap it with produce.\r\n const result = caseReducer(previousState as any, action)\r\n\r\n if (result === undefined) {\r\n if (previousState === null) {\r\n return previousState\r\n }\r\n throw Error(\r\n 'A case reducer on a non-draftable value must not return undefined'\r\n )\r\n }\r\n\r\n return result as S\r\n } else {\r\n // @ts-ignore createNextState() produces an Immutable> rather\r\n // than an Immutable, and TypeScript cannot find out how to reconcile\r\n // these two types.\r\n return createNextState(previousState, (draft: Draft) => {\r\n return caseReducer(draft, action)\r\n })\r\n }\r\n }\r\n\r\n return previousState\r\n }, state)\r\n }\r\n\r\n reducer.getInitialState = getInitialState\r\n\r\n return reducer as ReducerWithInitialState\r\n}\r\n", "import type { Action, AnyAction } from 'redux'\r\nimport type {\r\n CaseReducer,\r\n CaseReducers,\r\n ActionMatcherDescriptionCollection,\r\n} from './createReducer'\r\nimport type { TypeGuard } from './tsHelpers'\r\n\r\nexport interface TypedActionCreator {\r\n (...args: any[]): Action\r\n type: Type\r\n}\r\n\r\n/**\r\n * A builder for an action <-> reducer map.\r\n *\r\n * @public\r\n */\r\nexport interface ActionReducerMapBuilder {\r\n /**\r\n * Adds a case reducer to handle a single exact action type.\r\n * @remarks\r\n * All calls to `builder.addCase` must come before any calls to `builder.addMatcher` or `builder.addDefaultCase`.\r\n * @param actionCreator - Either a plain action type string, or an action creator generated by [`createAction`](./createAction) that can be used to determine the action type.\r\n * @param reducer - The actual case reducer function.\r\n */\r\n addCase>(\r\n actionCreator: ActionCreator,\r\n reducer: CaseReducer>\r\n ): ActionReducerMapBuilder\r\n /**\r\n * Adds a case reducer to handle a single exact action type.\r\n * @remarks\r\n * All calls to `builder.addCase` must come before any calls to `builder.addMatcher` or `builder.addDefaultCase`.\r\n * @param actionCreator - Either a plain action type string, or an action creator generated by [`createAction`](./createAction) that can be used to determine the action type.\r\n * @param reducer - The actual case reducer function.\r\n */\r\n addCase>(\r\n type: Type,\r\n reducer: CaseReducer\r\n ): ActionReducerMapBuilder\r\n\r\n /**\r\n * Allows you to match your incoming actions against your own filter function instead of only the `action.type` property.\r\n * @remarks\r\n * If multiple matcher reducers match, all of them will be executed in the order\r\n * they were defined in - even if a case reducer already matched.\r\n * All calls to `builder.addMatcher` must come after any calls to `builder.addCase` and before any calls to `builder.addDefaultCase`.\r\n * @param matcher - A matcher function. In TypeScript, this should be a [type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates)\r\n * function\r\n * @param reducer - The actual case reducer function.\r\n *\r\n * @example\r\n```ts\r\nimport {\r\n createAction,\r\n createReducer,\r\n AsyncThunk,\r\n AnyAction,\r\n} from \"@reduxjs/toolkit\";\r\n\r\ntype GenericAsyncThunk = AsyncThunk;\r\n\r\ntype PendingAction = ReturnType;\r\ntype RejectedAction = ReturnType;\r\ntype FulfilledAction = ReturnType;\r\n\r\nconst initialState: Record = {};\r\nconst resetAction = createAction(\"reset-tracked-loading-state\");\r\n\r\nfunction isPendingAction(action: AnyAction): action is PendingAction {\r\n return action.type.endsWith(\"/pending\");\r\n}\r\n\r\nconst reducer = createReducer(initialState, (builder) => {\r\n builder\r\n .addCase(resetAction, () => initialState)\r\n // matcher can be defined outside as a type predicate function\r\n .addMatcher(isPendingAction, (state, action) => {\r\n state[action.meta.requestId] = \"pending\";\r\n })\r\n .addMatcher(\r\n // matcher can be defined inline as a type predicate function\r\n (action): action is RejectedAction => action.type.endsWith(\"/rejected\"),\r\n (state, action) => {\r\n state[action.meta.requestId] = \"rejected\";\r\n }\r\n )\r\n // matcher can just return boolean and the matcher can receive a generic argument\r\n .addMatcher(\r\n (action) => action.type.endsWith(\"/fulfilled\"),\r\n (state, action) => {\r\n state[action.meta.requestId] = \"fulfilled\";\r\n }\r\n );\r\n});\r\n```\r\n */\r\n addMatcher(\r\n matcher: TypeGuard | ((action: any) => boolean),\r\n reducer: CaseReducer\r\n ): Omit, 'addCase'>\r\n\r\n /**\r\n * Adds a \"default case\" reducer that is executed if no case reducer and no matcher\r\n * reducer was executed for this action.\r\n * @param reducer - The fallback \"default case\" reducer function.\r\n *\r\n * @example\r\n```ts\r\nimport { createReducer } from '@reduxjs/toolkit'\r\nconst initialState = { otherActions: 0 }\r\nconst reducer = createReducer(initialState, builder => {\r\n builder\r\n // .addCase(...)\r\n // .addMatcher(...)\r\n .addDefaultCase((state, action) => {\r\n state.otherActions++\r\n })\r\n})\r\n```\r\n */\r\n addDefaultCase(reducer: CaseReducer): {}\r\n}\r\n\r\nexport function executeReducerBuilderCallback(\r\n builderCallback: (builder: ActionReducerMapBuilder) => void\r\n): [\r\n CaseReducers,\r\n ActionMatcherDescriptionCollection,\r\n CaseReducer | undefined\r\n] {\r\n const actionsMap: CaseReducers = {}\r\n const actionMatchers: ActionMatcherDescriptionCollection = []\r\n let defaultCaseReducer: CaseReducer | undefined\r\n const builder = {\r\n addCase(\r\n typeOrActionCreator: string | TypedActionCreator,\r\n reducer: CaseReducer\r\n ) {\r\n if (process.env.NODE_ENV !== 'production') {\r\n /*\r\n to keep the definition by the user in line with actual behavior,\r\n we enforce `addCase` to always be called before calling `addMatcher`\r\n as matching cases take precedence over matchers\r\n */\r\n if (actionMatchers.length > 0) {\r\n throw new Error(\r\n '`builder.addCase` should only be called before calling `builder.addMatcher`'\r\n )\r\n }\r\n if (defaultCaseReducer) {\r\n throw new Error(\r\n '`builder.addCase` should only be called before calling `builder.addDefaultCase`'\r\n )\r\n }\r\n }\r\n const type =\r\n typeof typeOrActionCreator === 'string'\r\n ? typeOrActionCreator\r\n : typeOrActionCreator.type\r\n if (!type) {\r\n throw new Error(\r\n '`builder.addCase` cannot be called with an empty action type'\r\n )\r\n }\r\n if (type in actionsMap) {\r\n throw new Error(\r\n '`builder.addCase` cannot be called with two reducers for the same action type'\r\n )\r\n }\r\n actionsMap[type] = reducer\r\n return builder\r\n },\r\n addMatcher(\r\n matcher: TypeGuard,\r\n reducer: CaseReducer\r\n ) {\r\n if (process.env.NODE_ENV !== 'production') {\r\n if (defaultCaseReducer) {\r\n throw new Error(\r\n '`builder.addMatcher` should only be called before calling `builder.addDefaultCase`'\r\n )\r\n }\r\n }\r\n actionMatchers.push({ matcher, reducer })\r\n return builder\r\n },\r\n addDefaultCase(reducer: CaseReducer) {\r\n if (process.env.NODE_ENV !== 'production') {\r\n if (defaultCaseReducer) {\r\n throw new Error('`builder.addDefaultCase` can only be called once')\r\n }\r\n }\r\n defaultCaseReducer = reducer\r\n return builder\r\n },\r\n }\r\n builderCallback(builder)\r\n return [actionsMap, actionMatchers, defaultCaseReducer]\r\n}\r\n", "import type { AnyAction, Reducer } from 'redux'\r\nimport { createNextState } from '.'\r\nimport type {\r\n ActionCreatorWithoutPayload,\r\n PayloadAction,\r\n PayloadActionCreator,\r\n PrepareAction,\r\n _ActionCreatorWithPreparedPayload,\r\n} from './createAction'\r\nimport { createAction } from './createAction'\r\nimport type {\r\n CaseReducer,\r\n CaseReducers,\r\n ReducerWithInitialState,\r\n} from './createReducer'\r\nimport { createReducer, NotFunction } from './createReducer'\r\nimport type { ActionReducerMapBuilder } from './mapBuilders'\r\nimport { executeReducerBuilderCallback } from './mapBuilders'\r\nimport type { NoInfer } from './tsHelpers'\r\nimport { freezeDraftable } from './utils'\r\n\r\nlet hasWarnedAboutObjectNotation = false\r\n\r\n/**\r\n * An action creator attached to a slice.\r\n *\r\n * @deprecated please use PayloadActionCreator directly\r\n *\r\n * @public\r\n */\r\nexport type SliceActionCreator

= PayloadActionCreator

\r\n\r\n/**\r\n * The return value of `createSlice`\r\n *\r\n * @public\r\n */\r\nexport interface Slice<\r\n State = any,\r\n CaseReducers extends SliceCaseReducers = SliceCaseReducers,\r\n Name extends string = string\r\n> {\r\n /**\r\n * The slice name.\r\n */\r\n name: Name\r\n\r\n /**\r\n * The slice's reducer.\r\n */\r\n reducer: Reducer\r\n\r\n /**\r\n * Action creators for the types of actions that are handled by the slice\r\n * reducer.\r\n */\r\n actions: CaseReducerActions\r\n\r\n /**\r\n * The individual case reducer functions that were passed in the `reducers` parameter.\r\n * This enables reuse and testing if they were defined inline when calling `createSlice`.\r\n */\r\n caseReducers: SliceDefinedCaseReducers\r\n\r\n /**\r\n * Provides access to the initial state value given to the slice.\r\n * If a lazy state initializer was provided, it will be called and a fresh value returned.\r\n */\r\n getInitialState: () => State\r\n}\r\n\r\n/**\r\n * Options for `createSlice()`.\r\n *\r\n * @public\r\n */\r\nexport interface CreateSliceOptions<\r\n State = any,\r\n CR extends SliceCaseReducers = SliceCaseReducers,\r\n Name extends string = string\r\n> {\r\n /**\r\n * The slice's name. Used to namespace the generated action types.\r\n */\r\n name: Name\r\n\r\n /**\r\n * The initial state that should be used when the reducer is called the first time. This may also be a \"lazy initializer\" function, which should return an initial state value when called. This will be used whenever the reducer is called with `undefined` as its state value, and is primarily useful for cases like reading initial state from `localStorage`.\r\n */\r\n initialState: State | (() => State)\r\n\r\n /**\r\n * A mapping from action types to action-type-specific *case reducer*\r\n * functions. For every action type, a matching action creator will be\r\n * generated using `createAction()`.\r\n */\r\n reducers: ValidateSliceCaseReducers\r\n\r\n /**\r\n * A callback that receives a *builder* object to define\r\n * case reducers via calls to `builder.addCase(actionCreatorOrType, reducer)`.\r\n * \r\n * Alternatively, a mapping from action types to action-type-specific *case reducer*\r\n * functions. These reducers should have existing action types used\r\n * as the keys, and action creators will _not_ be generated.\r\n * \r\n * @example\r\n```ts\r\nimport { createAction, createSlice, Action, AnyAction } from '@reduxjs/toolkit'\r\nconst incrementBy = createAction('incrementBy')\r\nconst decrement = createAction('decrement')\r\n\r\ninterface RejectedAction extends Action {\r\n error: Error\r\n}\r\n\r\nfunction isRejectedAction(action: AnyAction): action is RejectedAction {\r\n return action.type.endsWith('rejected')\r\n}\r\n\r\ncreateSlice({\r\n name: 'counter',\r\n initialState: 0,\r\n reducers: {},\r\n extraReducers: builder => {\r\n builder\r\n .addCase(incrementBy, (state, action) => {\r\n // action is inferred correctly here if using TS\r\n })\r\n // You can chain calls, or have separate `builder.addCase()` lines each time\r\n .addCase(decrement, (state, action) => {})\r\n // You can match a range of action types\r\n .addMatcher(\r\n isRejectedAction,\r\n // `action` will be inferred as a RejectedAction due to isRejectedAction being defined as a type guard\r\n (state, action) => {}\r\n )\r\n // and provide a default case if no other handlers matched\r\n .addDefaultCase((state, action) => {})\r\n }\r\n})\r\n```\r\n */\r\n extraReducers?:\r\n | CaseReducers, any>\r\n | ((builder: ActionReducerMapBuilder>) => void)\r\n}\r\n\r\n/**\r\n * A CaseReducer with a `prepare` method.\r\n *\r\n * @public\r\n */\r\nexport type CaseReducerWithPrepare = {\r\n reducer: CaseReducer\r\n prepare: PrepareAction\r\n}\r\n\r\n/**\r\n * The type describing a slice's `reducers` option.\r\n *\r\n * @public\r\n */\r\nexport type SliceCaseReducers = {\r\n [K: string]:\r\n | CaseReducer>\r\n | CaseReducerWithPrepare>\r\n}\r\n\r\ntype SliceActionType<\r\n SliceName extends string,\r\n ActionName extends keyof any\r\n> = ActionName extends string | number ? `${SliceName}/${ActionName}` : string\r\n\r\n/**\r\n * Derives the slice's `actions` property from the `reducers` options\r\n *\r\n * @public\r\n */\r\nexport type CaseReducerActions<\r\n CaseReducers extends SliceCaseReducers,\r\n SliceName extends string\r\n> = {\r\n [Type in keyof CaseReducers]: CaseReducers[Type] extends { prepare: any }\r\n ? ActionCreatorForCaseReducerWithPrepare<\r\n CaseReducers[Type],\r\n SliceActionType\r\n >\r\n : ActionCreatorForCaseReducer<\r\n CaseReducers[Type],\r\n SliceActionType\r\n >\r\n}\r\n\r\n/**\r\n * Get a `PayloadActionCreator` type for a passed `CaseReducerWithPrepare`\r\n *\r\n * @internal\r\n */\r\ntype ActionCreatorForCaseReducerWithPrepare<\r\n CR extends { prepare: any },\r\n Type extends string\r\n> = _ActionCreatorWithPreparedPayload\r\n\r\n/**\r\n * Get a `PayloadActionCreator` type for a passed `CaseReducer`\r\n *\r\n * @internal\r\n */\r\ntype ActionCreatorForCaseReducer = CR extends (\r\n state: any,\r\n action: infer Action\r\n) => any\r\n ? Action extends { payload: infer P }\r\n ? PayloadActionCreator\r\n : ActionCreatorWithoutPayload\r\n : ActionCreatorWithoutPayload\r\n\r\n/**\r\n * Extracts the CaseReducers out of a `reducers` object, even if they are\r\n * tested into a `CaseReducerWithPrepare`.\r\n *\r\n * @internal\r\n */\r\ntype SliceDefinedCaseReducers> = {\r\n [Type in keyof CaseReducers]: CaseReducers[Type] extends {\r\n reducer: infer Reducer\r\n }\r\n ? Reducer\r\n : CaseReducers[Type]\r\n}\r\n\r\n/**\r\n * Used on a SliceCaseReducers object.\r\n * Ensures that if a CaseReducer is a `CaseReducerWithPrepare`, that\r\n * the `reducer` and the `prepare` function use the same type of `payload`.\r\n *\r\n * Might do additional such checks in the future.\r\n *\r\n * This type is only ever useful if you want to write your own wrapper around\r\n * `createSlice`. Please don't use it otherwise!\r\n *\r\n * @public\r\n */\r\nexport type ValidateSliceCaseReducers<\r\n S,\r\n ACR extends SliceCaseReducers\r\n> = ACR &\r\n {\r\n [T in keyof ACR]: ACR[T] extends {\r\n reducer(s: S, action?: infer A): any\r\n }\r\n ? {\r\n prepare(...a: never[]): Omit\r\n }\r\n : {}\r\n }\r\n\r\nfunction getType(slice: string, actionKey: string): string {\r\n return `${slice}/${actionKey}`\r\n}\r\n\r\n/**\r\n * A function that accepts an initial state, an object full of reducer\r\n * functions, and a \"slice name\", and automatically generates\r\n * action creators and action types that correspond to the\r\n * reducers and state.\r\n *\r\n * The `reducer` argument is passed to `createReducer()`.\r\n *\r\n * @public\r\n */\r\nexport function createSlice<\r\n State,\r\n CaseReducers extends SliceCaseReducers,\r\n Name extends string = string\r\n>(\r\n options: CreateSliceOptions\r\n): Slice {\r\n const { name } = options\r\n if (!name) {\r\n throw new Error('`name` is a required option for createSlice')\r\n }\r\n\r\n if (\r\n typeof process !== 'undefined' &&\r\n process.env.NODE_ENV === 'development'\r\n ) {\r\n if (options.initialState === undefined) {\r\n console.error(\r\n 'You must provide an `initialState` value that is not `undefined`. You may have misspelled `initialState`'\r\n )\r\n }\r\n }\r\n\r\n const initialState =\r\n typeof options.initialState == 'function'\r\n ? options.initialState\r\n : freezeDraftable(options.initialState)\r\n\r\n const reducers = options.reducers || {}\r\n\r\n const reducerNames = Object.keys(reducers)\r\n\r\n const sliceCaseReducersByName: Record = {}\r\n const sliceCaseReducersByType: Record = {}\r\n const actionCreators: Record = {}\r\n\r\n reducerNames.forEach((reducerName) => {\r\n const maybeReducerWithPrepare = reducers[reducerName]\r\n const type = getType(name, reducerName)\r\n\r\n let caseReducer: CaseReducer\r\n let prepareCallback: PrepareAction | undefined\r\n\r\n if ('reducer' in maybeReducerWithPrepare) {\r\n caseReducer = maybeReducerWithPrepare.reducer\r\n prepareCallback = maybeReducerWithPrepare.prepare\r\n } else {\r\n caseReducer = maybeReducerWithPrepare\r\n }\r\n\r\n sliceCaseReducersByName[reducerName] = caseReducer\r\n sliceCaseReducersByType[type] = caseReducer\r\n actionCreators[reducerName] = prepareCallback\r\n ? createAction(type, prepareCallback)\r\n : createAction(type)\r\n })\r\n\r\n function buildReducer() {\r\n if (process.env.NODE_ENV !== 'production') {\r\n if (typeof options.extraReducers === 'object') {\r\n if (!hasWarnedAboutObjectNotation) {\r\n hasWarnedAboutObjectNotation = true\r\n console.warn(\r\n \"The object notation for `createSlice.extraReducers` is deprecated, and will be removed in RTK 2.0. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createSlice\"\r\n )\r\n }\r\n }\r\n }\r\n const [\r\n extraReducers = {},\r\n actionMatchers = [],\r\n defaultCaseReducer = undefined,\r\n ] =\r\n typeof options.extraReducers === 'function'\r\n ? executeReducerBuilderCallback(options.extraReducers)\r\n : [options.extraReducers]\r\n\r\n const finalCaseReducers = { ...extraReducers, ...sliceCaseReducersByType }\r\n\r\n return createReducer(initialState, (builder) => {\r\n for (let key in finalCaseReducers) {\r\n builder.addCase(key, finalCaseReducers[key] as CaseReducer)\r\n }\r\n for (let m of actionMatchers) {\r\n builder.addMatcher(m.matcher, m.reducer)\r\n }\r\n if (defaultCaseReducer) {\r\n builder.addDefaultCase(defaultCaseReducer)\r\n }\r\n })\r\n }\r\n\r\n let _reducer: ReducerWithInitialState\r\n\r\n return {\r\n name,\r\n reducer(state, action) {\r\n if (!_reducer) _reducer = buildReducer()\r\n\r\n return _reducer(state, action)\r\n },\r\n actions: actionCreators as any,\r\n caseReducers: sliceCaseReducersByName as any,\r\n getInitialState() {\r\n if (!_reducer) _reducer = buildReducer()\r\n\r\n return _reducer.getInitialState()\r\n },\r\n }\r\n}\r\n", "import type { EntityState } from './models'\r\n\r\nexport function getInitialEntityState(): EntityState {\r\n return {\r\n ids: [],\r\n entities: {},\r\n }\r\n}\r\n\r\nexport function createInitialStateFactory() {\r\n function getInitialState(): EntityState\r\n function getInitialState(\r\n additionalState: S\r\n ): EntityState & S\r\n function getInitialState(additionalState: any = {}): any {\r\n return Object.assign(getInitialEntityState(), additionalState)\r\n }\r\n\r\n return { getInitialState }\r\n}\r\n", "import type { Selector } from 'reselect'\r\nimport { createDraftSafeSelector } from '../createDraftSafeSelector'\r\nimport type {\r\n EntityState,\r\n EntitySelectors,\r\n Dictionary,\r\n EntityId,\r\n} from './models'\r\n\r\nexport function createSelectorsFactory() {\r\n function getSelectors(): EntitySelectors>\r\n function getSelectors(\r\n selectState: (state: V) => EntityState\r\n ): EntitySelectors\r\n function getSelectors(\r\n selectState?: (state: V) => EntityState\r\n ): EntitySelectors {\r\n const selectIds = (state: EntityState) => state.ids\r\n\r\n const selectEntities = (state: EntityState) => state.entities\r\n\r\n const selectAll = createDraftSafeSelector(\r\n selectIds,\r\n selectEntities,\r\n (ids, entities): T[] => ids.map((id) => entities[id]!)\r\n )\r\n\r\n const selectId = (_: unknown, id: EntityId) => id\r\n\r\n const selectById = (entities: Dictionary, id: EntityId) => entities[id]\r\n\r\n const selectTotal = createDraftSafeSelector(selectIds, (ids) => ids.length)\r\n\r\n if (!selectState) {\r\n return {\r\n selectIds,\r\n selectEntities,\r\n selectAll,\r\n selectTotal,\r\n selectById: createDraftSafeSelector(\r\n selectEntities,\r\n selectId,\r\n selectById\r\n ),\r\n }\r\n }\r\n\r\n const selectGlobalizedEntities = createDraftSafeSelector(\r\n selectState as Selector>,\r\n selectEntities\r\n )\r\n\r\n return {\r\n selectIds: createDraftSafeSelector(selectState, selectIds),\r\n selectEntities: selectGlobalizedEntities,\r\n selectAll: createDraftSafeSelector(selectState, selectAll),\r\n selectTotal: createDraftSafeSelector(selectState, selectTotal),\r\n selectById: createDraftSafeSelector(\r\n selectGlobalizedEntities,\r\n selectId,\r\n selectById\r\n ),\r\n }\r\n }\r\n\r\n return { getSelectors }\r\n}\r\n", "import createNextState, { isDraft } from 'immer'\r\nimport type { EntityState, PreventAny } from './models'\r\nimport type { PayloadAction } from '../createAction'\r\nimport { isFSA } from '../createAction'\r\nimport { IsAny } from '../tsHelpers'\r\n\r\nexport function createSingleArgumentStateOperator(\r\n mutator: (state: EntityState) => void\r\n) {\r\n const operator = createStateOperator((_: undefined, state: EntityState) =>\r\n mutator(state)\r\n )\r\n\r\n return function operation>(\r\n state: PreventAny\r\n ): S {\r\n return operator(state as S, undefined)\r\n }\r\n}\r\n\r\nexport function createStateOperator(\r\n mutator: (arg: R, state: EntityState) => void\r\n) {\r\n return function operation>(\r\n state: S,\r\n arg: R | PayloadAction\r\n ): S {\r\n function isPayloadActionArgument(\r\n arg: R | PayloadAction\r\n ): arg is PayloadAction {\r\n return isFSA(arg)\r\n }\r\n\r\n const runMutator = (draft: EntityState) => {\r\n if (isPayloadActionArgument(arg)) {\r\n mutator(arg.payload, draft)\r\n } else {\r\n mutator(arg, draft)\r\n }\r\n }\r\n\r\n if (isDraft(state)) {\r\n // we must already be inside a `createNextState` call, likely because\r\n // this is being wrapped in `createReducer` or `createSlice`.\r\n // It's safe to just pass the draft to the mutator.\r\n runMutator(state)\r\n\r\n // since it's a draft, we'll just return it\r\n return state\r\n } else {\r\n // @ts-ignore createNextState() produces an Immutable> rather\r\n // than an Immutable, and TypeScript cannot find out how to reconcile\r\n // these two types.\r\n return createNextState(state, runMutator)\r\n }\r\n }\r\n}\r\n", "import type { EntityState, IdSelector, Update, EntityId } from './models'\r\n\r\nexport function selectIdValue(entity: T, selectId: IdSelector) {\r\n const key = selectId(entity)\r\n\r\n if (process.env.NODE_ENV !== 'production' && key === undefined) {\r\n console.warn(\r\n 'The entity passed to the `selectId` implementation returned undefined.',\r\n 'You should probably provide your own `selectId` implementation.',\r\n 'The entity that was passed:',\r\n entity,\r\n 'The `selectId` implementation:',\r\n selectId.toString()\r\n )\r\n }\r\n\r\n return key\r\n}\r\n\r\nexport function ensureEntitiesArray(\r\n entities: readonly T[] | Record\r\n): readonly T[] {\r\n if (!Array.isArray(entities)) {\r\n entities = Object.values(entities)\r\n }\r\n\r\n return entities\r\n}\r\n\r\nexport function splitAddedUpdatedEntities(\r\n newEntities: readonly T[] | Record,\r\n selectId: IdSelector,\r\n state: EntityState\r\n): [T[], Update[]] {\r\n newEntities = ensureEntitiesArray(newEntities)\r\n\r\n const added: T[] = []\r\n const updated: Update[] = []\r\n\r\n for (const entity of newEntities) {\r\n const id = selectIdValue(entity, selectId)\r\n if (id in state.entities) {\r\n updated.push({ id, changes: entity })\r\n } else {\r\n added.push(entity)\r\n }\r\n }\r\n return [added, updated]\r\n}\r\n", "import type {\r\n EntityState,\r\n EntityStateAdapter,\r\n IdSelector,\r\n Update,\r\n EntityId,\r\n} from './models'\r\nimport {\r\n createStateOperator,\r\n createSingleArgumentStateOperator,\r\n} from './state_adapter'\r\nimport {\r\n selectIdValue,\r\n ensureEntitiesArray,\r\n splitAddedUpdatedEntities,\r\n} from './utils'\r\n\r\nexport function createUnsortedStateAdapter(\r\n selectId: IdSelector\r\n): EntityStateAdapter {\r\n type R = EntityState\r\n\r\n function addOneMutably(entity: T, state: R): void {\r\n const key = selectIdValue(entity, selectId)\r\n\r\n if (key in state.entities) {\r\n return\r\n }\r\n\r\n state.ids.push(key)\r\n state.entities[key] = entity\r\n }\r\n\r\n function addManyMutably(\r\n newEntities: readonly T[] | Record,\r\n state: R\r\n ): void {\r\n newEntities = ensureEntitiesArray(newEntities)\r\n\r\n for (const entity of newEntities) {\r\n addOneMutably(entity, state)\r\n }\r\n }\r\n\r\n function setOneMutably(entity: T, state: R): void {\r\n const key = selectIdValue(entity, selectId)\r\n if (!(key in state.entities)) {\r\n state.ids.push(key)\r\n }\r\n state.entities[key] = entity\r\n }\r\n\r\n function setManyMutably(\r\n newEntities: readonly T[] | Record,\r\n state: R\r\n ): void {\r\n newEntities = ensureEntitiesArray(newEntities)\r\n for (const entity of newEntities) {\r\n setOneMutably(entity, state)\r\n }\r\n }\r\n\r\n function setAllMutably(\r\n newEntities: readonly T[] | Record,\r\n state: R\r\n ): void {\r\n newEntities = ensureEntitiesArray(newEntities)\r\n\r\n state.ids = []\r\n state.entities = {}\r\n\r\n addManyMutably(newEntities, state)\r\n }\r\n\r\n function removeOneMutably(key: EntityId, state: R): void {\r\n return removeManyMutably([key], state)\r\n }\r\n\r\n function removeManyMutably(keys: readonly EntityId[], state: R): void {\r\n let didMutate = false\r\n\r\n keys.forEach((key) => {\r\n if (key in state.entities) {\r\n delete state.entities[key]\r\n didMutate = true\r\n }\r\n })\r\n\r\n if (didMutate) {\r\n state.ids = state.ids.filter((id) => id in state.entities)\r\n }\r\n }\r\n\r\n function removeAllMutably(state: R): void {\r\n Object.assign(state, {\r\n ids: [],\r\n entities: {},\r\n })\r\n }\r\n\r\n function takeNewKey(\r\n keys: { [id: string]: EntityId },\r\n update: Update,\r\n state: R\r\n ): boolean {\r\n const original = state.entities[update.id]\r\n const updated: T = Object.assign({}, original, update.changes)\r\n const newKey = selectIdValue(updated, selectId)\r\n const hasNewKey = newKey !== update.id\r\n\r\n if (hasNewKey) {\r\n keys[update.id] = newKey\r\n delete state.entities[update.id]\r\n }\r\n\r\n state.entities[newKey] = updated\r\n\r\n return hasNewKey\r\n }\r\n\r\n function updateOneMutably(update: Update, state: R): void {\r\n return updateManyMutably([update], state)\r\n }\r\n\r\n function updateManyMutably(\r\n updates: ReadonlyArray>,\r\n state: R\r\n ): void {\r\n const newKeys: { [id: string]: EntityId } = {}\r\n\r\n const updatesPerEntity: { [id: string]: Update } = {}\r\n\r\n updates.forEach((update) => {\r\n // Only apply updates to entities that currently exist\r\n if (update.id in state.entities) {\r\n // If there are multiple updates to one entity, merge them together\r\n updatesPerEntity[update.id] = {\r\n id: update.id,\r\n // Spreads ignore falsy values, so this works even if there isn't\r\n // an existing update already at this key\r\n changes: {\r\n ...(updatesPerEntity[update.id]\r\n ? updatesPerEntity[update.id].changes\r\n : null),\r\n ...update.changes,\r\n },\r\n }\r\n }\r\n })\r\n\r\n updates = Object.values(updatesPerEntity)\r\n\r\n const didMutateEntities = updates.length > 0\r\n\r\n if (didMutateEntities) {\r\n const didMutateIds =\r\n updates.filter((update) => takeNewKey(newKeys, update, state)).length >\r\n 0\r\n\r\n if (didMutateIds) {\r\n state.ids = Object.keys(state.entities)\r\n }\r\n }\r\n }\r\n\r\n function upsertOneMutably(entity: T, state: R): void {\r\n return upsertManyMutably([entity], state)\r\n }\r\n\r\n function upsertManyMutably(\r\n newEntities: readonly T[] | Record,\r\n state: R\r\n ): void {\r\n const [added, updated] = splitAddedUpdatedEntities(\r\n newEntities,\r\n selectId,\r\n state\r\n )\r\n\r\n updateManyMutably(updated, state)\r\n addManyMutably(added, state)\r\n }\r\n\r\n return {\r\n removeAll: createSingleArgumentStateOperator(removeAllMutably),\r\n addOne: createStateOperator(addOneMutably),\r\n addMany: createStateOperator(addManyMutably),\r\n setOne: createStateOperator(setOneMutably),\r\n setMany: createStateOperator(setManyMutably),\r\n setAll: createStateOperator(setAllMutably),\r\n updateOne: createStateOperator(updateOneMutably),\r\n updateMany: createStateOperator(updateManyMutably),\r\n upsertOne: createStateOperator(upsertOneMutably),\r\n upsertMany: createStateOperator(upsertManyMutably),\r\n removeOne: createStateOperator(removeOneMutably),\r\n removeMany: createStateOperator(removeManyMutably),\r\n }\r\n}\r\n", "import type {\r\n EntityState,\r\n IdSelector,\r\n Comparer,\r\n EntityStateAdapter,\r\n Update,\r\n EntityId,\r\n} from './models'\r\nimport { createStateOperator } from './state_adapter'\r\nimport { createUnsortedStateAdapter } from './unsorted_state_adapter'\r\nimport {\r\n selectIdValue,\r\n ensureEntitiesArray,\r\n splitAddedUpdatedEntities,\r\n} from './utils'\r\n\r\nexport function createSortedStateAdapter(\r\n selectId: IdSelector,\r\n sort: Comparer\r\n): EntityStateAdapter {\r\n type R = EntityState\r\n\r\n const { removeOne, removeMany, removeAll } =\r\n createUnsortedStateAdapter(selectId)\r\n\r\n function addOneMutably(entity: T, state: R): void {\r\n return addManyMutably([entity], state)\r\n }\r\n\r\n function addManyMutably(\r\n newEntities: readonly T[] | Record,\r\n state: R\r\n ): void {\r\n newEntities = ensureEntitiesArray(newEntities)\r\n\r\n const models = newEntities.filter(\r\n (model) => !(selectIdValue(model, selectId) in state.entities)\r\n )\r\n\r\n if (models.length !== 0) {\r\n merge(models, state)\r\n }\r\n }\r\n\r\n function setOneMutably(entity: T, state: R): void {\r\n return setManyMutably([entity], state)\r\n }\r\n\r\n function setManyMutably(\r\n newEntities: readonly T[] | Record,\r\n state: R\r\n ): void {\r\n newEntities = ensureEntitiesArray(newEntities)\r\n if (newEntities.length !== 0) {\r\n merge(newEntities, state)\r\n }\r\n }\r\n\r\n function setAllMutably(\r\n newEntities: readonly T[] | Record,\r\n state: R\r\n ): void {\r\n newEntities = ensureEntitiesArray(newEntities)\r\n state.entities = {}\r\n state.ids = []\r\n\r\n addManyMutably(newEntities, state)\r\n }\r\n\r\n function updateOneMutably(update: Update, state: R): void {\r\n return updateManyMutably([update], state)\r\n }\r\n\r\n function updateManyMutably(\r\n updates: ReadonlyArray>,\r\n state: R\r\n ): void {\r\n let appliedUpdates = false\r\n\r\n for (let update of updates) {\r\n const entity = state.entities[update.id]\r\n if (!entity) {\r\n continue\r\n }\r\n\r\n appliedUpdates = true\r\n\r\n Object.assign(entity, update.changes)\r\n const newId = selectId(entity)\r\n if (update.id !== newId) {\r\n delete state.entities[update.id]\r\n state.entities[newId] = entity\r\n }\r\n }\r\n\r\n if (appliedUpdates) {\r\n resortEntities(state)\r\n }\r\n }\r\n\r\n function upsertOneMutably(entity: T, state: R): void {\r\n return upsertManyMutably([entity], state)\r\n }\r\n\r\n function upsertManyMutably(\r\n newEntities: readonly T[] | Record,\r\n state: R\r\n ): void {\r\n const [added, updated] = splitAddedUpdatedEntities(\r\n newEntities,\r\n selectId,\r\n state\r\n )\r\n\r\n updateManyMutably(updated, state)\r\n addManyMutably(added, state)\r\n }\r\n\r\n function areArraysEqual(a: readonly unknown[], b: readonly unknown[]) {\r\n if (a.length !== b.length) {\r\n return false\r\n }\r\n\r\n for (let i = 0; i < a.length && i < b.length; i++) {\r\n if (a[i] === b[i]) {\r\n continue\r\n }\r\n return false\r\n }\r\n return true\r\n }\r\n\r\n function merge(models: readonly T[], state: R): void {\r\n // Insert/overwrite all new/updated\r\n models.forEach((model) => {\r\n state.entities[selectId(model)] = model\r\n })\r\n\r\n resortEntities(state)\r\n }\r\n\r\n function resortEntities(state: R) {\r\n const allEntities = Object.values(state.entities) as T[]\r\n allEntities.sort(sort)\r\n\r\n const newSortedIds = allEntities.map(selectId)\r\n const { ids } = state\r\n\r\n if (!areArraysEqual(ids, newSortedIds)) {\r\n state.ids = newSortedIds\r\n }\r\n }\r\n\r\n return {\r\n removeOne,\r\n removeMany,\r\n removeAll,\r\n addOne: createStateOperator(addOneMutably),\r\n updateOne: createStateOperator(updateOneMutably),\r\n upsertOne: createStateOperator(upsertOneMutably),\r\n setOne: createStateOperator(setOneMutably),\r\n setMany: createStateOperator(setManyMutably),\r\n setAll: createStateOperator(setAllMutably),\r\n addMany: createStateOperator(addManyMutably),\r\n updateMany: createStateOperator(updateManyMutably),\r\n upsertMany: createStateOperator(upsertManyMutably),\r\n }\r\n}\r\n", "import type {\r\n EntityDefinition,\r\n Comparer,\r\n IdSelector,\r\n EntityAdapter,\r\n} from './models'\r\nimport { createInitialStateFactory } from './entity_state'\r\nimport { createSelectorsFactory } from './state_selectors'\r\nimport { createSortedStateAdapter } from './sorted_state_adapter'\r\nimport { createUnsortedStateAdapter } from './unsorted_state_adapter'\r\n\r\n/**\r\n *\r\n * @param options\r\n *\r\n * @public\r\n */\r\nexport function createEntityAdapter(\r\n options: {\r\n selectId?: IdSelector\r\n sortComparer?: false | Comparer\r\n } = {}\r\n): EntityAdapter {\r\n const { selectId, sortComparer }: EntityDefinition = {\r\n sortComparer: false,\r\n selectId: (instance: any) => instance.id,\r\n ...options,\r\n }\r\n\r\n const stateFactory = createInitialStateFactory()\r\n const selectorsFactory = createSelectorsFactory()\r\n const stateAdapter = sortComparer\r\n ? createSortedStateAdapter(selectId, sortComparer)\r\n : createUnsortedStateAdapter(selectId)\r\n\r\n return {\r\n selectId,\r\n sortComparer,\r\n ...stateFactory,\r\n ...selectorsFactory,\r\n ...stateAdapter,\r\n }\r\n}\r\n", "// Borrowed from https://github.com/ai/nanoid/blob/3.0.2/non-secure/index.js\r\n// This alphabet uses `A-Za-z0-9_-` symbols. A genetic algorithm helped\r\n// optimize the gzip compression for this alphabet.\r\nlet urlAlphabet =\r\n 'ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW'\r\n\r\n/**\r\n *\r\n * @public\r\n */\r\nexport let nanoid = (size = 21) => {\r\n let id = ''\r\n // A compact alternative for `for (var i = 0; i < step; i++)`.\r\n let i = size\r\n while (i--) {\r\n // `| 0` is more compact and faster than `Math.floor()`.\r\n id += urlAlphabet[(Math.random() * 64) | 0]\r\n }\r\n return id\r\n}\r\n", "import type { Dispatch, AnyAction } from 'redux'\r\nimport type {\r\n PayloadAction,\r\n ActionCreatorWithPreparedPayload,\r\n} from './createAction'\r\nimport { createAction } from './createAction'\r\nimport type { ThunkDispatch } from 'redux-thunk'\r\nimport type { FallbackIfUnknown, Id, IsAny, IsUnknown } from './tsHelpers'\r\nimport { nanoid } from './nanoid'\r\n\r\n// @ts-ignore we need the import of these types due to a bundling issue.\r\ntype _Keep = PayloadAction | ActionCreatorWithPreparedPayload\r\n\r\nexport type BaseThunkAPI<\r\n S,\r\n E,\r\n D extends Dispatch = Dispatch,\r\n RejectedValue = unknown,\r\n RejectedMeta = unknown,\r\n FulfilledMeta = unknown\r\n> = {\r\n dispatch: D\r\n getState: () => S\r\n extra: E\r\n requestId: string\r\n signal: AbortSignal\r\n abort: (reason?: string) => void\r\n rejectWithValue: IsUnknown<\r\n RejectedMeta,\r\n (value: RejectedValue) => RejectWithValue,\r\n (\r\n value: RejectedValue,\r\n meta: RejectedMeta\r\n ) => RejectWithValue\r\n >\r\n fulfillWithValue: IsUnknown<\r\n FulfilledMeta,\r\n (value: FulfilledValue) => FulfilledValue,\r\n (\r\n value: FulfilledValue,\r\n meta: FulfilledMeta\r\n ) => FulfillWithMeta\r\n >\r\n}\r\n\r\n/**\r\n * @public\r\n */\r\nexport interface SerializedError {\r\n name?: string\r\n message?: string\r\n stack?: string\r\n code?: string\r\n}\r\n\r\nconst commonProperties: Array = [\r\n 'name',\r\n 'message',\r\n 'stack',\r\n 'code',\r\n]\r\n\r\nclass RejectWithValue {\r\n /*\r\n type-only property to distinguish between RejectWithValue and FulfillWithMeta\r\n does not exist at runtime\r\n */\r\n private readonly _type!: 'RejectWithValue'\r\n constructor(\r\n public readonly payload: Payload,\r\n public readonly meta: RejectedMeta\r\n ) {}\r\n}\r\n\r\nclass FulfillWithMeta {\r\n /*\r\n type-only property to distinguish between RejectWithValue and FulfillWithMeta\r\n does not exist at runtime\r\n */\r\n private readonly _type!: 'FulfillWithMeta'\r\n constructor(\r\n public readonly payload: Payload,\r\n public readonly meta: FulfilledMeta\r\n ) {}\r\n}\r\n\r\n/**\r\n * Serializes an error into a plain object.\r\n * Reworked from https://github.com/sindresorhus/serialize-error\r\n *\r\n * @public\r\n */\r\nexport const miniSerializeError = (value: any): SerializedError => {\r\n if (typeof value === 'object' && value !== null) {\r\n const simpleError: SerializedError = {}\r\n for (const property of commonProperties) {\r\n if (typeof value[property] === 'string') {\r\n simpleError[property] = value[property]\r\n }\r\n }\r\n\r\n return simpleError\r\n }\r\n\r\n return { message: String(value) }\r\n}\r\n\r\ntype AsyncThunkConfig = {\r\n state?: unknown\r\n dispatch?: Dispatch\r\n extra?: unknown\r\n rejectValue?: unknown\r\n serializedErrorType?: unknown\r\n pendingMeta?: unknown\r\n fulfilledMeta?: unknown\r\n rejectedMeta?: unknown\r\n}\r\n\r\ntype GetState = ThunkApiConfig extends {\r\n state: infer State\r\n}\r\n ? State\r\n : unknown\r\ntype GetExtra = ThunkApiConfig extends { extra: infer Extra }\r\n ? Extra\r\n : unknown\r\ntype GetDispatch = ThunkApiConfig extends {\r\n dispatch: infer Dispatch\r\n}\r\n ? FallbackIfUnknown<\r\n Dispatch,\r\n ThunkDispatch<\r\n GetState,\r\n GetExtra,\r\n AnyAction\r\n >\r\n >\r\n : ThunkDispatch, GetExtra, AnyAction>\r\n\r\nexport type GetThunkAPI = BaseThunkAPI<\r\n GetState,\r\n GetExtra,\r\n GetDispatch,\r\n GetRejectValue,\r\n GetRejectedMeta,\r\n GetFulfilledMeta\r\n>\r\n\r\ntype GetRejectValue = ThunkApiConfig extends {\r\n rejectValue: infer RejectValue\r\n}\r\n ? RejectValue\r\n : unknown\r\n\r\ntype GetPendingMeta = ThunkApiConfig extends {\r\n pendingMeta: infer PendingMeta\r\n}\r\n ? PendingMeta\r\n : unknown\r\n\r\ntype GetFulfilledMeta = ThunkApiConfig extends {\r\n fulfilledMeta: infer FulfilledMeta\r\n}\r\n ? FulfilledMeta\r\n : unknown\r\n\r\ntype GetRejectedMeta = ThunkApiConfig extends {\r\n rejectedMeta: infer RejectedMeta\r\n}\r\n ? RejectedMeta\r\n : unknown\r\n\r\ntype GetSerializedErrorType = ThunkApiConfig extends {\r\n serializedErrorType: infer GetSerializedErrorType\r\n}\r\n ? GetSerializedErrorType\r\n : SerializedError\r\n\r\ntype MaybePromise = T | Promise | (T extends any ? Promise : never)\r\n\r\n/**\r\n * A type describing the return value of the `payloadCreator` argument to `createAsyncThunk`.\r\n * Might be useful for wrapping `createAsyncThunk` in custom abstractions.\r\n *\r\n * @public\r\n */\r\nexport type AsyncThunkPayloadCreatorReturnValue<\r\n Returned,\r\n ThunkApiConfig extends AsyncThunkConfig\r\n> = MaybePromise<\r\n | IsUnknown<\r\n GetFulfilledMeta,\r\n Returned,\r\n FulfillWithMeta>\r\n >\r\n | RejectWithValue<\r\n GetRejectValue,\r\n GetRejectedMeta\r\n >\r\n>\r\n/**\r\n * A type describing the `payloadCreator` argument to `createAsyncThunk`.\r\n * Might be useful for wrapping `createAsyncThunk` in custom abstractions.\r\n *\r\n * @public\r\n */\r\nexport type AsyncThunkPayloadCreator<\r\n Returned,\r\n ThunkArg = void,\r\n ThunkApiConfig extends AsyncThunkConfig = {}\r\n> = (\r\n arg: ThunkArg,\r\n thunkAPI: GetThunkAPI\r\n) => AsyncThunkPayloadCreatorReturnValue\r\n\r\n/**\r\n * A ThunkAction created by `createAsyncThunk`.\r\n * Dispatching it returns a Promise for either a\r\n * fulfilled or rejected action.\r\n * Also, the returned value contains an `abort()` method\r\n * that allows the asyncAction to be cancelled from the outside.\r\n *\r\n * @public\r\n */\r\nexport type AsyncThunkAction<\r\n Returned,\r\n ThunkArg,\r\n ThunkApiConfig extends AsyncThunkConfig\r\n> = (\r\n dispatch: GetDispatch,\r\n getState: () => GetState,\r\n extra: GetExtra\r\n) => Promise<\r\n | ReturnType>\r\n | ReturnType>\r\n> & {\r\n abort: (reason?: string) => void\r\n requestId: string\r\n arg: ThunkArg\r\n unwrap: () => Promise\r\n}\r\n\r\ntype AsyncThunkActionCreator<\r\n Returned,\r\n ThunkArg,\r\n ThunkApiConfig extends AsyncThunkConfig\r\n> = IsAny<\r\n ThunkArg,\r\n // any handling\r\n (arg: ThunkArg) => AsyncThunkAction,\r\n // unknown handling\r\n unknown extends ThunkArg\r\n ? (arg: ThunkArg) => AsyncThunkAction // argument not specified or specified as void or undefined\r\n : [ThunkArg] extends [void] | [undefined]\r\n ? () => AsyncThunkAction // argument contains void\r\n : [void] extends [ThunkArg] // make optional\r\n ? (arg?: ThunkArg) => AsyncThunkAction // argument contains undefined\r\n : [undefined] extends [ThunkArg]\r\n ? WithStrictNullChecks<\r\n // with strict nullChecks: make optional\r\n (\r\n arg?: ThunkArg\r\n ) => AsyncThunkAction,\r\n // without strict null checks this will match everything, so don't make it optional\r\n (arg: ThunkArg) => AsyncThunkAction\r\n > // default case: normal argument\r\n : (arg: ThunkArg) => AsyncThunkAction\r\n>\r\n\r\n/**\r\n * Options object for `createAsyncThunk`.\r\n *\r\n * @public\r\n */\r\nexport type AsyncThunkOptions<\r\n ThunkArg = void,\r\n ThunkApiConfig extends AsyncThunkConfig = {}\r\n> = {\r\n /**\r\n * A method to control whether the asyncThunk should be executed. Has access to the\r\n * `arg`, `api.getState()` and `api.extra` arguments.\r\n *\r\n * @returns `false` if it should be skipped\r\n */\r\n condition?(\r\n arg: ThunkArg,\r\n api: Pick, 'getState' | 'extra'>\r\n ): MaybePromise\r\n /**\r\n * If `condition` returns `false`, the asyncThunk will be skipped.\r\n * This option allows you to control whether a `rejected` action with `meta.condition == false`\r\n * will be dispatched or not.\r\n *\r\n * @default `false`\r\n */\r\n dispatchConditionRejection?: boolean\r\n\r\n serializeError?: (x: unknown) => GetSerializedErrorType\r\n\r\n /**\r\n * A function to use when generating the `requestId` for the request sequence.\r\n *\r\n * @default `nanoid`\r\n */\r\n idGenerator?: (arg: ThunkArg) => string\r\n} & IsUnknown<\r\n GetPendingMeta,\r\n {\r\n /**\r\n * A method to generate additional properties to be added to `meta` of the pending action.\r\n *\r\n * Using this optional overload will not modify the types correctly, this overload is only in place to support JavaScript users.\r\n * Please use the `ThunkApiConfig` parameter `pendingMeta` to get access to a correctly typed overload\r\n */\r\n getPendingMeta?(\r\n base: {\r\n arg: ThunkArg\r\n requestId: string\r\n },\r\n api: Pick, 'getState' | 'extra'>\r\n ): GetPendingMeta\r\n },\r\n {\r\n /**\r\n * A method to generate additional properties to be added to `meta` of the pending action.\r\n */\r\n getPendingMeta(\r\n base: {\r\n arg: ThunkArg\r\n requestId: string\r\n },\r\n api: Pick, 'getState' | 'extra'>\r\n ): GetPendingMeta\r\n }\r\n>\r\n\r\nexport type AsyncThunkPendingActionCreator<\r\n ThunkArg,\r\n ThunkApiConfig = {}\r\n> = ActionCreatorWithPreparedPayload<\r\n [string, ThunkArg, GetPendingMeta?],\r\n undefined,\r\n string,\r\n never,\r\n {\r\n arg: ThunkArg\r\n requestId: string\r\n requestStatus: 'pending'\r\n } & GetPendingMeta\r\n>\r\n\r\nexport type AsyncThunkRejectedActionCreator<\r\n ThunkArg,\r\n ThunkApiConfig = {}\r\n> = ActionCreatorWithPreparedPayload<\r\n [\r\n Error | null,\r\n string,\r\n ThunkArg,\r\n GetRejectValue?,\r\n GetRejectedMeta?\r\n ],\r\n GetRejectValue | undefined,\r\n string,\r\n GetSerializedErrorType,\r\n {\r\n arg: ThunkArg\r\n requestId: string\r\n requestStatus: 'rejected'\r\n aborted: boolean\r\n condition: boolean\r\n } & (\r\n | ({ rejectedWithValue: false } & {\r\n [K in keyof GetRejectedMeta]?: undefined\r\n })\r\n | ({ rejectedWithValue: true } & GetRejectedMeta)\r\n )\r\n>\r\n\r\nexport type AsyncThunkFulfilledActionCreator<\r\n Returned,\r\n ThunkArg,\r\n ThunkApiConfig = {}\r\n> = ActionCreatorWithPreparedPayload<\r\n [Returned, string, ThunkArg, GetFulfilledMeta?],\r\n Returned,\r\n string,\r\n never,\r\n {\r\n arg: ThunkArg\r\n requestId: string\r\n requestStatus: 'fulfilled'\r\n } & GetFulfilledMeta\r\n>\r\n\r\n/**\r\n * A type describing the return value of `createAsyncThunk`.\r\n * Might be useful for wrapping `createAsyncThunk` in custom abstractions.\r\n *\r\n * @public\r\n */\r\nexport type AsyncThunk<\r\n Returned,\r\n ThunkArg,\r\n ThunkApiConfig extends AsyncThunkConfig\r\n> = AsyncThunkActionCreator & {\r\n pending: AsyncThunkPendingActionCreator\r\n rejected: AsyncThunkRejectedActionCreator\r\n fulfilled: AsyncThunkFulfilledActionCreator<\r\n Returned,\r\n ThunkArg,\r\n ThunkApiConfig\r\n >\r\n typePrefix: string\r\n}\r\n\r\ntype OverrideThunkApiConfigs = Id<\r\n NewConfig & Omit\r\n>\r\n\r\ntype CreateAsyncThunk = {\r\n /**\r\n *\r\n * @param typePrefix\r\n * @param payloadCreator\r\n * @param options\r\n *\r\n * @public\r\n */\r\n // separate signature without `AsyncThunkConfig` for better inference\r\n (\r\n typePrefix: string,\r\n payloadCreator: AsyncThunkPayloadCreator<\r\n Returned,\r\n ThunkArg,\r\n CurriedThunkApiConfig\r\n >,\r\n options?: AsyncThunkOptions\r\n ): AsyncThunk\r\n\r\n /**\r\n *\r\n * @param typePrefix\r\n * @param payloadCreator\r\n * @param options\r\n *\r\n * @public\r\n */\r\n (\r\n typePrefix: string,\r\n payloadCreator: AsyncThunkPayloadCreator<\r\n Returned,\r\n ThunkArg,\r\n OverrideThunkApiConfigs\r\n >,\r\n options?: AsyncThunkOptions<\r\n ThunkArg,\r\n OverrideThunkApiConfigs\r\n >\r\n ): AsyncThunk<\r\n Returned,\r\n ThunkArg,\r\n OverrideThunkApiConfigs\r\n >\r\n\r\n withTypes(): CreateAsyncThunk<\r\n OverrideThunkApiConfigs\r\n >\r\n}\r\n\r\nexport const createAsyncThunk = (() => {\r\n function createAsyncThunk<\r\n Returned,\r\n ThunkArg,\r\n ThunkApiConfig extends AsyncThunkConfig\r\n >(\r\n typePrefix: string,\r\n payloadCreator: AsyncThunkPayloadCreator<\r\n Returned,\r\n ThunkArg,\r\n ThunkApiConfig\r\n >,\r\n options?: AsyncThunkOptions\r\n ): AsyncThunk {\r\n type RejectedValue = GetRejectValue\r\n type PendingMeta = GetPendingMeta\r\n type FulfilledMeta = GetFulfilledMeta\r\n type RejectedMeta = GetRejectedMeta\r\n\r\n const fulfilled: AsyncThunkFulfilledActionCreator<\r\n Returned,\r\n ThunkArg,\r\n ThunkApiConfig\r\n > = createAction(\r\n typePrefix + '/fulfilled',\r\n (\r\n payload: Returned,\r\n requestId: string,\r\n arg: ThunkArg,\r\n meta?: FulfilledMeta\r\n ) => ({\r\n payload,\r\n meta: {\r\n ...((meta as any) || {}),\r\n arg,\r\n requestId,\r\n requestStatus: 'fulfilled' as const,\r\n },\r\n })\r\n )\r\n\r\n const pending: AsyncThunkPendingActionCreator =\r\n createAction(\r\n typePrefix + '/pending',\r\n (requestId: string, arg: ThunkArg, meta?: PendingMeta) => ({\r\n payload: undefined,\r\n meta: {\r\n ...((meta as any) || {}),\r\n arg,\r\n requestId,\r\n requestStatus: 'pending' as const,\r\n },\r\n })\r\n )\r\n\r\n const rejected: AsyncThunkRejectedActionCreator =\r\n createAction(\r\n typePrefix + '/rejected',\r\n (\r\n error: Error | null,\r\n requestId: string,\r\n arg: ThunkArg,\r\n payload?: RejectedValue,\r\n meta?: RejectedMeta\r\n ) => ({\r\n payload,\r\n error: ((options && options.serializeError) || miniSerializeError)(\r\n error || 'Rejected'\r\n ) as GetSerializedErrorType,\r\n meta: {\r\n ...((meta as any) || {}),\r\n arg,\r\n requestId,\r\n rejectedWithValue: !!payload,\r\n requestStatus: 'rejected' as const,\r\n aborted: error?.name === 'AbortError',\r\n condition: error?.name === 'ConditionError',\r\n },\r\n })\r\n )\r\n\r\n let displayedWarning = false\r\n\r\n const AC =\r\n typeof AbortController !== 'undefined'\r\n ? AbortController\r\n : class implements AbortController {\r\n signal = {\r\n aborted: false,\r\n addEventListener() {},\r\n dispatchEvent() {\r\n return false\r\n },\r\n onabort() {},\r\n removeEventListener() {},\r\n reason: undefined,\r\n throwIfAborted() {},\r\n }\r\n abort() {\r\n if (process.env.NODE_ENV !== 'production') {\r\n if (!displayedWarning) {\r\n displayedWarning = true\r\n console.info(\r\n `This platform does not implement AbortController. \r\nIf you want to use the AbortController to react to \\`abort\\` events, please consider importing a polyfill like 'abortcontroller-polyfill/dist/abortcontroller-polyfill-only'.`\r\n )\r\n }\r\n }\r\n }\r\n }\r\n\r\n function actionCreator(\r\n arg: ThunkArg\r\n ): AsyncThunkAction {\r\n return (dispatch, getState, extra) => {\r\n const requestId = options?.idGenerator\r\n ? options.idGenerator(arg)\r\n : nanoid()\r\n\r\n const abortController = new AC()\r\n let abortReason: string | undefined\r\n\r\n let started = false\r\n function abort(reason?: string) {\r\n abortReason = reason\r\n abortController.abort()\r\n }\r\n\r\n const promise = (async function () {\r\n let finalAction: ReturnType\r\n try {\r\n let conditionResult = options?.condition?.(arg, { getState, extra })\r\n if (isThenable(conditionResult)) {\r\n conditionResult = await conditionResult\r\n }\r\n\r\n if (conditionResult === false || abortController.signal.aborted) {\r\n // eslint-disable-next-line no-throw-literal\r\n throw {\r\n name: 'ConditionError',\r\n message: 'Aborted due to condition callback returning false.',\r\n }\r\n }\r\n started = true\r\n\r\n const abortedPromise = new Promise((_, reject) =>\r\n abortController.signal.addEventListener('abort', () =>\r\n reject({\r\n name: 'AbortError',\r\n message: abortReason || 'Aborted',\r\n })\r\n )\r\n )\r\n dispatch(\r\n pending(\r\n requestId,\r\n arg,\r\n options?.getPendingMeta?.(\r\n { requestId, arg },\r\n { getState, extra }\r\n )\r\n )\r\n )\r\n finalAction = await Promise.race([\r\n abortedPromise,\r\n Promise.resolve(\r\n payloadCreator(arg, {\r\n dispatch,\r\n getState,\r\n extra,\r\n requestId,\r\n signal: abortController.signal,\r\n abort,\r\n rejectWithValue: ((\r\n value: RejectedValue,\r\n meta?: RejectedMeta\r\n ) => {\r\n return new RejectWithValue(value, meta)\r\n }) as any,\r\n fulfillWithValue: ((value: unknown, meta?: FulfilledMeta) => {\r\n return new FulfillWithMeta(value, meta)\r\n }) as any,\r\n })\r\n ).then((result) => {\r\n if (result instanceof RejectWithValue) {\r\n throw result\r\n }\r\n if (result instanceof FulfillWithMeta) {\r\n return fulfilled(result.payload, requestId, arg, result.meta)\r\n }\r\n return fulfilled(result as any, requestId, arg)\r\n }),\r\n ])\r\n } catch (err) {\r\n finalAction =\r\n err instanceof RejectWithValue\r\n ? rejected(null, requestId, arg, err.payload, err.meta)\r\n : rejected(err as any, requestId, arg)\r\n }\r\n // We dispatch the result action _after_ the catch, to avoid having any errors\r\n // here get swallowed by the try/catch block,\r\n // per https://twitter.com/dan_abramov/status/770914221638942720\r\n // and https://github.com/reduxjs/redux-toolkit/blob/e85eb17b39a2118d859f7b7746e0f3fee523e089/docs/tutorials/advanced-tutorial.md#async-error-handling-logic-in-thunks\r\n\r\n const skipDispatch =\r\n options &&\r\n !options.dispatchConditionRejection &&\r\n rejected.match(finalAction) &&\r\n (finalAction as any).meta.condition\r\n\r\n if (!skipDispatch) {\r\n dispatch(finalAction)\r\n }\r\n return finalAction\r\n })()\r\n return Object.assign(promise as Promise, {\r\n abort,\r\n requestId,\r\n arg,\r\n unwrap() {\r\n return promise.then(unwrapResult)\r\n },\r\n })\r\n }\r\n }\r\n\r\n return Object.assign(\r\n actionCreator as AsyncThunkActionCreator<\r\n Returned,\r\n ThunkArg,\r\n ThunkApiConfig\r\n >,\r\n {\r\n pending,\r\n rejected,\r\n fulfilled,\r\n typePrefix,\r\n }\r\n )\r\n }\r\n createAsyncThunk.withTypes = () => createAsyncThunk\r\n\r\n return createAsyncThunk as CreateAsyncThunk\r\n})()\r\n\r\ninterface UnwrappableAction {\r\n payload: any\r\n meta?: any\r\n error?: any\r\n}\r\n\r\ntype UnwrappedActionPayload = Exclude<\r\n T,\r\n { error: any }\r\n>['payload']\r\n\r\n/**\r\n * @public\r\n */\r\nexport function unwrapResult(\r\n action: R\r\n): UnwrappedActionPayload {\r\n if (action.meta && action.meta.rejectedWithValue) {\r\n throw action.payload\r\n }\r\n if (action.error) {\r\n throw action.error\r\n }\r\n return action.payload\r\n}\r\n\r\ntype WithStrictNullChecks = undefined extends boolean\r\n ? False\r\n : True\r\n\r\nfunction isThenable(value: any): value is PromiseLike {\r\n return (\r\n value !== null &&\r\n typeof value === 'object' &&\r\n typeof value.then === 'function'\r\n )\r\n}\r\n", "import type {\r\n ActionFromMatcher,\r\n Matcher,\r\n UnionToIntersection,\r\n} from './tsHelpers'\r\nimport { hasMatchFunction } from './tsHelpers'\r\nimport type {\r\n AsyncThunk,\r\n AsyncThunkFulfilledActionCreator,\r\n AsyncThunkPendingActionCreator,\r\n AsyncThunkRejectedActionCreator,\r\n} from './createAsyncThunk'\r\n\r\n/** @public */\r\nexport type ActionMatchingAnyOf[]]> =\r\n ActionFromMatcher\r\n\r\n/** @public */\r\nexport type ActionMatchingAllOf[]]> =\r\n UnionToIntersection>\r\n\r\nconst matches = (matcher: Matcher, action: any) => {\r\n if (hasMatchFunction(matcher)) {\r\n return matcher.match(action)\r\n } else {\r\n return matcher(action)\r\n }\r\n}\r\n\r\n/**\r\n * A higher-order function that returns a function that may be used to check\r\n * whether an action matches any one of the supplied type guards or action\r\n * creators.\r\n *\r\n * @param matchers The type guards or action creators to match against.\r\n *\r\n * @public\r\n */\r\nexport function isAnyOf[]]>(\r\n ...matchers: Matchers\r\n) {\r\n return (action: any): action is ActionMatchingAnyOf => {\r\n return matchers.some((matcher) => matches(matcher, action))\r\n }\r\n}\r\n\r\n/**\r\n * A higher-order function that returns a function that may be used to check\r\n * whether an action matches all of the supplied type guards or action\r\n * creators.\r\n *\r\n * @param matchers The type guards or action creators to match against.\r\n *\r\n * @public\r\n */\r\nexport function isAllOf[]]>(\r\n ...matchers: Matchers\r\n) {\r\n return (action: any): action is ActionMatchingAllOf => {\r\n return matchers.every((matcher) => matches(matcher, action))\r\n }\r\n}\r\n\r\n/**\r\n * @param action A redux action\r\n * @param validStatus An array of valid meta.requestStatus values\r\n *\r\n * @internal\r\n */\r\nexport function hasExpectedRequestMetadata(\r\n action: any,\r\n validStatus: readonly string[]\r\n) {\r\n if (!action || !action.meta) return false\r\n\r\n const hasValidRequestId = typeof action.meta.requestId === 'string'\r\n const hasValidRequestStatus =\r\n validStatus.indexOf(action.meta.requestStatus) > -1\r\n\r\n return hasValidRequestId && hasValidRequestStatus\r\n}\r\n\r\nfunction isAsyncThunkArray(a: [any] | AnyAsyncThunk[]): a is AnyAsyncThunk[] {\r\n return (\r\n typeof a[0] === 'function' &&\r\n 'pending' in a[0] &&\r\n 'fulfilled' in a[0] &&\r\n 'rejected' in a[0]\r\n )\r\n}\r\n\r\nexport type UnknownAsyncThunkPendingAction = ReturnType<\r\n AsyncThunkPendingActionCreator\r\n>\r\n\r\nexport type PendingActionFromAsyncThunk =\r\n ActionFromMatcher\r\n\r\n/**\r\n * A higher-order function that returns a function that may be used to check\r\n * whether an action was created by an async thunk action creator, and that\r\n * the action is pending.\r\n *\r\n * @public\r\n */\r\nexport function isPending(): (\r\n action: any\r\n) => action is UnknownAsyncThunkPendingAction\r\n/**\r\n * A higher-order function that returns a function that may be used to check\r\n * whether an action belongs to one of the provided async thunk action creators,\r\n * and that the action is pending.\r\n *\r\n * @param asyncThunks (optional) The async thunk action creators to match against.\r\n *\r\n * @public\r\n */\r\nexport function isPending<\r\n AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]\r\n>(\r\n ...asyncThunks: AsyncThunks\r\n): (action: any) => action is PendingActionFromAsyncThunk\r\n/**\r\n * Tests if `action` is a pending thunk action\r\n * @public\r\n */\r\nexport function isPending(action: any): action is UnknownAsyncThunkPendingAction\r\nexport function isPending<\r\n AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]\r\n>(...asyncThunks: AsyncThunks | [any]) {\r\n if (asyncThunks.length === 0) {\r\n return (action: any) => hasExpectedRequestMetadata(action, ['pending'])\r\n }\r\n\r\n if (!isAsyncThunkArray(asyncThunks)) {\r\n return isPending()(asyncThunks[0])\r\n }\r\n\r\n return (\r\n action: any\r\n ): action is PendingActionFromAsyncThunk => {\r\n // note: this type will be correct because we have at least 1 asyncThunk\r\n const matchers: [Matcher, ...Matcher[]] = asyncThunks.map(\r\n (asyncThunk) => asyncThunk.pending\r\n ) as any\r\n\r\n const combinedMatcher = isAnyOf(...matchers)\r\n\r\n return combinedMatcher(action)\r\n }\r\n}\r\n\r\nexport type UnknownAsyncThunkRejectedAction = ReturnType<\r\n AsyncThunkRejectedActionCreator\r\n>\r\n\r\nexport type RejectedActionFromAsyncThunk =\r\n ActionFromMatcher\r\n\r\n/**\r\n * A higher-order function that returns a function that may be used to check\r\n * whether an action was created by an async thunk action creator, and that\r\n * the action is rejected.\r\n *\r\n * @public\r\n */\r\nexport function isRejected(): (\r\n action: any\r\n) => action is UnknownAsyncThunkRejectedAction\r\n/**\r\n * A higher-order function that returns a function that may be used to check\r\n * whether an action belongs to one of the provided async thunk action creators,\r\n * and that the action is rejected.\r\n *\r\n * @param asyncThunks (optional) The async thunk action creators to match against.\r\n *\r\n * @public\r\n */\r\nexport function isRejected<\r\n AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]\r\n>(\r\n ...asyncThunks: AsyncThunks\r\n): (action: any) => action is RejectedActionFromAsyncThunk\r\n/**\r\n * Tests if `action` is a rejected thunk action\r\n * @public\r\n */\r\nexport function isRejected(\r\n action: any\r\n): action is UnknownAsyncThunkRejectedAction\r\nexport function isRejected<\r\n AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]\r\n>(...asyncThunks: AsyncThunks | [any]) {\r\n if (asyncThunks.length === 0) {\r\n return (action: any) => hasExpectedRequestMetadata(action, ['rejected'])\r\n }\r\n\r\n if (!isAsyncThunkArray(asyncThunks)) {\r\n return isRejected()(asyncThunks[0])\r\n }\r\n\r\n return (\r\n action: any\r\n ): action is RejectedActionFromAsyncThunk => {\r\n // note: this type will be correct because we have at least 1 asyncThunk\r\n const matchers: [Matcher, ...Matcher[]] = asyncThunks.map(\r\n (asyncThunk) => asyncThunk.rejected\r\n ) as any\r\n\r\n const combinedMatcher = isAnyOf(...matchers)\r\n\r\n return combinedMatcher(action)\r\n }\r\n}\r\n\r\nexport type UnknownAsyncThunkRejectedWithValueAction = ReturnType<\r\n AsyncThunkRejectedActionCreator\r\n>\r\n\r\nexport type RejectedWithValueActionFromAsyncThunk =\r\n ActionFromMatcher &\r\n (T extends AsyncThunk\r\n ? { payload: RejectedValue }\r\n : unknown)\r\n\r\n/**\r\n * A higher-order function that returns a function that may be used to check\r\n * whether an action was created by an async thunk action creator, and that\r\n * the action is rejected with value.\r\n *\r\n * @public\r\n */\r\nexport function isRejectedWithValue(): (\r\n action: any\r\n) => action is UnknownAsyncThunkRejectedAction\r\n/**\r\n * A higher-order function that returns a function that may be used to check\r\n * whether an action belongs to one of the provided async thunk action creators,\r\n * and that the action is rejected with value.\r\n *\r\n * @param asyncThunks (optional) The async thunk action creators to match against.\r\n *\r\n * @public\r\n */\r\nexport function isRejectedWithValue<\r\n AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]\r\n>(\r\n ...asyncThunks: AsyncThunks\r\n): (\r\n action: any\r\n) => action is RejectedWithValueActionFromAsyncThunk\r\n/**\r\n * Tests if `action` is a rejected thunk action with value\r\n * @public\r\n */\r\nexport function isRejectedWithValue(\r\n action: any\r\n): action is UnknownAsyncThunkRejectedAction\r\nexport function isRejectedWithValue<\r\n AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]\r\n>(...asyncThunks: AsyncThunks | [any]) {\r\n const hasFlag = (action: any): action is any => {\r\n return action && action.meta && action.meta.rejectedWithValue\r\n }\r\n\r\n if (asyncThunks.length === 0) {\r\n return (action: any) => {\r\n const combinedMatcher = isAllOf(isRejected(...asyncThunks), hasFlag)\r\n\r\n return combinedMatcher(action)\r\n }\r\n }\r\n\r\n if (!isAsyncThunkArray(asyncThunks)) {\r\n return isRejectedWithValue()(asyncThunks[0])\r\n }\r\n\r\n return (\r\n action: any\r\n ): action is RejectedActionFromAsyncThunk => {\r\n const combinedMatcher = isAllOf(isRejected(...asyncThunks), hasFlag)\r\n\r\n return combinedMatcher(action)\r\n }\r\n}\r\n\r\nexport type UnknownAsyncThunkFulfilledAction = ReturnType<\r\n AsyncThunkFulfilledActionCreator\r\n>\r\n\r\nexport type FulfilledActionFromAsyncThunk =\r\n ActionFromMatcher\r\n\r\n/**\r\n * A higher-order function that returns a function that may be used to check\r\n * whether an action was created by an async thunk action creator, and that\r\n * the action is fulfilled.\r\n *\r\n * @public\r\n */\r\nexport function isFulfilled(): (\r\n action: any\r\n) => action is UnknownAsyncThunkFulfilledAction\r\n/**\r\n * A higher-order function that returns a function that may be used to check\r\n * whether an action belongs to one of the provided async thunk action creators,\r\n * and that the action is fulfilled.\r\n *\r\n * @param asyncThunks (optional) The async thunk action creators to match against.\r\n *\r\n * @public\r\n */\r\nexport function isFulfilled<\r\n AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]\r\n>(\r\n ...asyncThunks: AsyncThunks\r\n): (action: any) => action is FulfilledActionFromAsyncThunk\r\n/**\r\n * Tests if `action` is a fulfilled thunk action\r\n * @public\r\n */\r\nexport function isFulfilled(\r\n action: any\r\n): action is UnknownAsyncThunkFulfilledAction\r\nexport function isFulfilled<\r\n AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]\r\n>(...asyncThunks: AsyncThunks | [any]) {\r\n if (asyncThunks.length === 0) {\r\n return (action: any) => hasExpectedRequestMetadata(action, ['fulfilled'])\r\n }\r\n\r\n if (!isAsyncThunkArray(asyncThunks)) {\r\n return isFulfilled()(asyncThunks[0])\r\n }\r\n\r\n return (\r\n action: any\r\n ): action is FulfilledActionFromAsyncThunk => {\r\n // note: this type will be correct because we have at least 1 asyncThunk\r\n const matchers: [Matcher, ...Matcher[]] = asyncThunks.map(\r\n (asyncThunk) => asyncThunk.fulfilled\r\n ) as any\r\n\r\n const combinedMatcher = isAnyOf(...matchers)\r\n\r\n return combinedMatcher(action)\r\n }\r\n}\r\n\r\nexport type UnknownAsyncThunkAction =\r\n | UnknownAsyncThunkPendingAction\r\n | UnknownAsyncThunkRejectedAction\r\n | UnknownAsyncThunkFulfilledAction\r\n\r\nexport type AnyAsyncThunk = {\r\n pending: { match: (action: any) => action is any }\r\n fulfilled: { match: (action: any) => action is any }\r\n rejected: { match: (action: any) => action is any }\r\n}\r\n\r\nexport type ActionsFromAsyncThunk =\r\n | ActionFromMatcher\r\n | ActionFromMatcher\r\n | ActionFromMatcher\r\n\r\n/**\r\n * A higher-order function that returns a function that may be used to check\r\n * whether an action was created by an async thunk action creator.\r\n *\r\n * @public\r\n */\r\nexport function isAsyncThunkAction(): (\r\n action: any\r\n) => action is UnknownAsyncThunkAction\r\n/**\r\n * A higher-order function that returns a function that may be used to check\r\n * whether an action belongs to one of the provided async thunk action creators.\r\n *\r\n * @param asyncThunks (optional) The async thunk action creators to match against.\r\n *\r\n * @public\r\n */\r\nexport function isAsyncThunkAction<\r\n AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]\r\n>(\r\n ...asyncThunks: AsyncThunks\r\n): (action: any) => action is ActionsFromAsyncThunk\r\n/**\r\n * Tests if `action` is a thunk action\r\n * @public\r\n */\r\nexport function isAsyncThunkAction(\r\n action: any\r\n): action is UnknownAsyncThunkAction\r\nexport function isAsyncThunkAction<\r\n AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]\r\n>(...asyncThunks: AsyncThunks | [any]) {\r\n if (asyncThunks.length === 0) {\r\n return (action: any) =>\r\n hasExpectedRequestMetadata(action, ['pending', 'fulfilled', 'rejected'])\r\n }\r\n\r\n if (!isAsyncThunkArray(asyncThunks)) {\r\n return isAsyncThunkAction()(asyncThunks[0])\r\n }\r\n\r\n return (\r\n action: any\r\n ): action is ActionsFromAsyncThunk => {\r\n // note: this type will be correct because we have at least 1 asyncThunk\r\n const matchers: [Matcher, ...Matcher[]] = [] as any\r\n\r\n for (const asyncThunk of asyncThunks) {\r\n matchers.push(\r\n asyncThunk.pending,\r\n asyncThunk.rejected,\r\n asyncThunk.fulfilled\r\n )\r\n }\r\n\r\n const combinedMatcher = isAnyOf(...matchers)\r\n\r\n return combinedMatcher(action)\r\n }\r\n}\r\n", "import type { AbortSignalWithReason } from './types'\r\n\r\nexport const assertFunction: (\r\n func: unknown,\r\n expected: string\r\n) => asserts func is (...args: unknown[]) => unknown = (\r\n func: unknown,\r\n expected: string\r\n) => {\r\n if (typeof func !== 'function') {\r\n throw new TypeError(`${expected} is not a function`)\r\n }\r\n}\r\n\r\nexport const noop = () => {}\r\n\r\nexport const catchRejection = (\r\n promise: Promise,\r\n onError = noop\r\n): Promise => {\r\n promise.catch(onError)\r\n\r\n return promise\r\n}\r\n\r\nexport const addAbortSignalListener = (\r\n abortSignal: AbortSignal,\r\n callback: (evt: Event) => void\r\n) => {\r\n abortSignal.addEventListener('abort', callback, { once: true })\r\n return () => abortSignal.removeEventListener('abort', callback)\r\n}\r\n\r\n/**\r\n * Calls `abortController.abort(reason)` and patches `signal.reason`.\r\n * if it is not supported.\r\n *\r\n * At the time of writing `signal.reason` is available in FF chrome, edge node 17 and deno.\r\n * @param abortController\r\n * @param reason\r\n * @returns\r\n * @see https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/reason\r\n */\r\nexport const abortControllerWithReason = (\r\n abortController: AbortController,\r\n reason: T\r\n): void => {\r\n type Consumer = (val: T) => void\r\n\r\n const signal = abortController.signal as AbortSignalWithReason\r\n\r\n if (signal.aborted) {\r\n return\r\n }\r\n\r\n // Patch `reason` if necessary.\r\n // - We use defineProperty here because reason is a getter of `AbortSignal.__proto__`.\r\n // - We need to patch 'reason' before calling `.abort()` because listeners to the 'abort'\r\n // event are are notified immediately.\r\n if (!('reason' in signal)) {\r\n Object.defineProperty(signal, 'reason', {\r\n enumerable: true,\r\n value: reason,\r\n configurable: true,\r\n writable: true,\r\n })\r\n }\r\n\r\n ;(abortController.abort as Consumer)(reason)\r\n}\r\n", "import type { SerializedError } from '@reduxjs/toolkit'\r\n\r\nconst task = 'task'\r\nconst listener = 'listener'\r\nconst completed = 'completed'\r\nconst cancelled = 'cancelled'\r\n\r\n/* TaskAbortError error codes */\r\nexport const taskCancelled = `task-${cancelled}` as const\r\nexport const taskCompleted = `task-${completed}` as const\r\nexport const listenerCancelled = `${listener}-${cancelled}` as const\r\nexport const listenerCompleted = `${listener}-${completed}` as const\r\n\r\nexport class TaskAbortError implements SerializedError {\r\n name = 'TaskAbortError'\r\n message: string\r\n constructor(public code: string | undefined) {\r\n this.message = `${task} ${cancelled} (reason: ${code})`\r\n }\r\n}\r\n", "import { TaskAbortError } from './exceptions'\r\nimport type { AbortSignalWithReason, TaskResult } from './types'\r\nimport { addAbortSignalListener, catchRejection, noop } from './utils'\r\n\r\n/**\r\n * Synchronously raises {@link TaskAbortError} if the task tied to the input `signal` has been cancelled.\r\n * @param signal\r\n * @param reason\r\n * @see {TaskAbortError}\r\n */\r\nexport const validateActive = (signal: AbortSignal): void => {\r\n if (signal.aborted) {\r\n throw new TaskAbortError((signal as AbortSignalWithReason).reason)\r\n }\r\n}\r\n\r\n/**\r\n * Generates a race between the promise(s) and the AbortSignal\r\n * This avoids `Promise.race()`-related memory leaks:\r\n * https://github.com/nodejs/node/issues/17469#issuecomment-349794909\r\n */\r\nexport function raceWithSignal(\r\n signal: AbortSignalWithReason,\r\n promise: Promise\r\n): Promise {\r\n let cleanup = noop\r\n return new Promise((resolve, reject) => {\r\n const notifyRejection = () => reject(new TaskAbortError(signal.reason))\r\n\r\n if (signal.aborted) {\r\n notifyRejection()\r\n return\r\n }\r\n\r\n cleanup = addAbortSignalListener(signal, notifyRejection)\r\n promise.finally(() => cleanup()).then(resolve, reject)\r\n }).finally(() => {\r\n // after this point, replace `cleanup` with a noop, so there is no reference to `signal` any more\r\n cleanup = noop\r\n })\r\n}\r\n\r\n/**\r\n * Runs a task and returns promise that resolves to {@link TaskResult}.\r\n * Second argument is an optional `cleanUp` function that always runs after task.\r\n *\r\n * **Note:** `runTask` runs the executor in the next microtask.\r\n * @returns\r\n */\r\nexport const runTask = async (\r\n task: () => Promise,\r\n cleanUp?: () => void\r\n): Promise> => {\r\n try {\r\n await Promise.resolve()\r\n const value = await task()\r\n return {\r\n status: 'ok',\r\n value,\r\n }\r\n } catch (error: any) {\r\n return {\r\n status: error instanceof TaskAbortError ? 'cancelled' : 'rejected',\r\n error,\r\n }\r\n } finally {\r\n cleanUp?.()\r\n }\r\n}\r\n\r\n/**\r\n * Given an input `AbortSignal` and a promise returns another promise that resolves\r\n * as soon the input promise is provided or rejects as soon as\r\n * `AbortSignal.abort` is `true`.\r\n * @param signal\r\n * @returns\r\n */\r\nexport const createPause = (signal: AbortSignal) => {\r\n return (promise: Promise): Promise => {\r\n return catchRejection(\r\n raceWithSignal(signal, promise).then((output) => {\r\n validateActive(signal)\r\n return output\r\n })\r\n )\r\n }\r\n}\r\n\r\n/**\r\n * Given an input `AbortSignal` and `timeoutMs` returns a promise that resolves\r\n * after `timeoutMs` or rejects as soon as `AbortSignal.abort` is `true`.\r\n * @param signal\r\n * @returns\r\n */\r\nexport const createDelay = (signal: AbortSignal) => {\r\n const pause = createPause(signal)\r\n return (timeoutMs: number): Promise => {\r\n return pause(new Promise((resolve) => setTimeout(resolve, timeoutMs)))\r\n }\r\n}\r\n", "import type { Dispatch, AnyAction, MiddlewareAPI } from 'redux'\r\nimport type { ThunkDispatch } from 'redux-thunk'\r\nimport { createAction, isAction } from '../createAction'\r\nimport { nanoid } from '../nanoid'\r\n\r\nimport type {\r\n ListenerMiddleware,\r\n ListenerMiddlewareInstance,\r\n AddListenerOverloads,\r\n AnyListenerPredicate,\r\n CreateListenerMiddlewareOptions,\r\n TypedAddListener,\r\n TypedCreateListenerEntry,\r\n FallbackAddListenerOptions,\r\n ListenerEntry,\r\n ListenerErrorHandler,\r\n UnsubscribeListener,\r\n TakePattern,\r\n ListenerErrorInfo,\r\n ForkedTaskExecutor,\r\n ForkedTask,\r\n TypedRemoveListener,\r\n TaskResult,\r\n AbortSignalWithReason,\r\n UnsubscribeListenerOptions,\r\n ForkOptions,\r\n} from './types'\r\nimport {\r\n abortControllerWithReason,\r\n addAbortSignalListener,\r\n assertFunction,\r\n catchRejection,\r\n} from './utils'\r\nimport {\r\n listenerCancelled,\r\n listenerCompleted,\r\n TaskAbortError,\r\n taskCancelled,\r\n taskCompleted,\r\n} from './exceptions'\r\nimport {\r\n runTask,\r\n validateActive,\r\n createPause,\r\n createDelay,\r\n raceWithSignal,\r\n} from './task'\r\nexport { TaskAbortError } from './exceptions'\r\nexport type {\r\n ListenerEffect,\r\n ListenerMiddleware,\r\n ListenerEffectAPI,\r\n ListenerMiddlewareInstance,\r\n CreateListenerMiddlewareOptions,\r\n ListenerErrorHandler,\r\n TypedStartListening,\r\n TypedAddListener,\r\n TypedStopListening,\r\n TypedRemoveListener,\r\n UnsubscribeListener,\r\n UnsubscribeListenerOptions,\r\n ForkedTaskExecutor,\r\n ForkedTask,\r\n ForkedTaskAPI,\r\n AsyncTaskExecutor,\r\n SyncTaskExecutor,\r\n TaskCancelled,\r\n TaskRejected,\r\n TaskResolved,\r\n TaskResult,\r\n} from './types'\r\n\r\n//Overly-aggressive byte-shaving\r\nconst { assign } = Object\r\n/**\r\n * @internal\r\n */\r\nconst INTERNAL_NIL_TOKEN = {} as const\r\n\r\nconst alm = 'listenerMiddleware' as const\r\n\r\nconst createFork = (\r\n parentAbortSignal: AbortSignalWithReason,\r\n parentBlockingPromises: Promise[]\r\n) => {\r\n const linkControllers = (controller: AbortController) =>\r\n addAbortSignalListener(parentAbortSignal, () =>\r\n abortControllerWithReason(controller, parentAbortSignal.reason)\r\n )\r\n\r\n return (\r\n taskExecutor: ForkedTaskExecutor,\r\n opts?: ForkOptions\r\n ): ForkedTask => {\r\n assertFunction(taskExecutor, 'taskExecutor')\r\n const childAbortController = new AbortController()\r\n\r\n linkControllers(childAbortController)\r\n\r\n const result = runTask(\r\n async (): Promise => {\r\n validateActive(parentAbortSignal)\r\n validateActive(childAbortController.signal)\r\n const result = (await taskExecutor({\r\n pause: createPause(childAbortController.signal),\r\n delay: createDelay(childAbortController.signal),\r\n signal: childAbortController.signal,\r\n })) as T\r\n validateActive(childAbortController.signal)\r\n return result\r\n },\r\n () => abortControllerWithReason(childAbortController, taskCompleted)\r\n )\r\n\r\n if (opts?.autoJoin) {\r\n parentBlockingPromises.push(result)\r\n }\r\n\r\n return {\r\n result: createPause>(parentAbortSignal)(result),\r\n cancel() {\r\n abortControllerWithReason(childAbortController, taskCancelled)\r\n },\r\n }\r\n }\r\n}\r\n\r\nconst createTakePattern = (\r\n startListening: AddListenerOverloads<\r\n UnsubscribeListener,\r\n S,\r\n Dispatch\r\n >,\r\n signal: AbortSignal\r\n): TakePattern => {\r\n /**\r\n * A function that takes a ListenerPredicate and an optional timeout,\r\n * and resolves when either the predicate returns `true` based on an action\r\n * state combination or when the timeout expires.\r\n * If the parent listener is canceled while waiting, this will throw a\r\n * TaskAbortError.\r\n */\r\n const take = async

>(\r\n predicate: P,\r\n timeout: number | undefined\r\n ) => {\r\n validateActive(signal)\r\n\r\n // Placeholder unsubscribe function until the listener is added\r\n let unsubscribe: UnsubscribeListener = () => {}\r\n\r\n const tuplePromise = new Promise<[AnyAction, S, S]>((resolve, reject) => {\r\n // Inside the Promise, we synchronously add the listener.\r\n let stopListening = startListening({\r\n predicate: predicate as any,\r\n effect: (action, listenerApi): void => {\r\n // One-shot listener that cleans up as soon as the predicate passes\r\n listenerApi.unsubscribe()\r\n // Resolve the promise with the same arguments the predicate saw\r\n resolve([\r\n action,\r\n listenerApi.getState(),\r\n listenerApi.getOriginalState(),\r\n ])\r\n },\r\n })\r\n unsubscribe = () => {\r\n stopListening()\r\n reject()\r\n }\r\n })\r\n\r\n const promises: (Promise | Promise<[AnyAction, S, S]>)[] = [\r\n tuplePromise,\r\n ]\r\n\r\n if (timeout != null) {\r\n promises.push(\r\n new Promise((resolve) => setTimeout(resolve, timeout, null))\r\n )\r\n }\r\n\r\n try {\r\n const output = await raceWithSignal(signal, Promise.race(promises))\r\n\r\n validateActive(signal)\r\n return output\r\n } finally {\r\n // Always clean up the listener\r\n unsubscribe()\r\n }\r\n }\r\n\r\n return ((predicate: AnyListenerPredicate, timeout: number | undefined) =>\r\n catchRejection(take(predicate, timeout))) as TakePattern\r\n}\r\n\r\nconst getListenerEntryPropsFrom = (options: FallbackAddListenerOptions) => {\r\n let { type, actionCreator, matcher, predicate, effect } = options\r\n\r\n if (type) {\r\n predicate = createAction(type).match\r\n } else if (actionCreator) {\r\n type = actionCreator!.type\r\n predicate = actionCreator.match\r\n } else if (matcher) {\r\n predicate = matcher\r\n } else if (predicate) {\r\n // pass\r\n } else {\r\n throw new Error(\r\n 'Creating or removing a listener requires one of the known fields for matching an action'\r\n )\r\n }\r\n\r\n assertFunction(effect, 'options.listener')\r\n\r\n return { predicate, type, effect }\r\n}\r\n\r\n/** Accepts the possible options for creating a listener, and returns a formatted listener entry */\r\nexport const createListenerEntry: TypedCreateListenerEntry = (\r\n options: FallbackAddListenerOptions\r\n) => {\r\n const { type, predicate, effect } = getListenerEntryPropsFrom(options)\r\n\r\n const id = nanoid()\r\n const entry: ListenerEntry = {\r\n id,\r\n effect,\r\n type,\r\n predicate,\r\n pending: new Set(),\r\n unsubscribe: () => {\r\n throw new Error('Unsubscribe not initialized')\r\n },\r\n }\r\n\r\n return entry\r\n}\r\n\r\nconst cancelActiveListeners = (\r\n entry: ListenerEntry>\r\n) => {\r\n entry.pending.forEach((controller) => {\r\n abortControllerWithReason(controller, listenerCancelled)\r\n })\r\n}\r\n\r\nconst createClearListenerMiddleware = (\r\n listenerMap: Map\r\n) => {\r\n return () => {\r\n listenerMap.forEach(cancelActiveListeners)\r\n\r\n listenerMap.clear()\r\n }\r\n}\r\n\r\n/**\r\n * Safely reports errors to the `errorHandler` provided.\r\n * Errors that occur inside `errorHandler` are notified in a new task.\r\n * Inspired by [rxjs reportUnhandledError](https://github.com/ReactiveX/rxjs/blob/6fafcf53dc9e557439b25debaeadfd224b245a66/src/internal/util/reportUnhandledError.ts)\r\n * @param errorHandler\r\n * @param errorToNotify\r\n */\r\nconst safelyNotifyError = (\r\n errorHandler: ListenerErrorHandler,\r\n errorToNotify: unknown,\r\n errorInfo: ListenerErrorInfo\r\n): void => {\r\n try {\r\n errorHandler(errorToNotify, errorInfo)\r\n } catch (errorHandlerError) {\r\n // We cannot let an error raised here block the listener queue.\r\n // The error raised here will be picked up by `window.onerror`, `process.on('error')` etc...\r\n setTimeout(() => {\r\n throw errorHandlerError\r\n }, 0)\r\n }\r\n}\r\n\r\n/**\r\n * @public\r\n */\r\nexport const addListener = createAction(\r\n `${alm}/add`\r\n) as TypedAddListener\r\n\r\n/**\r\n * @public\r\n */\r\nexport const clearAllListeners = createAction(`${alm}/removeAll`)\r\n\r\n/**\r\n * @public\r\n */\r\nexport const removeListener = createAction(\r\n `${alm}/remove`\r\n) as TypedRemoveListener\r\n\r\nconst defaultErrorHandler: ListenerErrorHandler = (...args: unknown[]) => {\r\n console.error(`${alm}/error`, ...args)\r\n}\r\n\r\n/**\r\n * @public\r\n */\r\nexport function createListenerMiddleware<\r\n S = unknown,\r\n D extends Dispatch = ThunkDispatch,\r\n ExtraArgument = unknown\r\n>(middlewareOptions: CreateListenerMiddlewareOptions = {}) {\r\n const listenerMap = new Map()\r\n const { extra, onError = defaultErrorHandler } = middlewareOptions\r\n\r\n assertFunction(onError, 'onError')\r\n\r\n const insertEntry = (entry: ListenerEntry) => {\r\n entry.unsubscribe = () => listenerMap.delete(entry!.id)\r\n\r\n listenerMap.set(entry.id, entry)\r\n return (cancelOptions?: UnsubscribeListenerOptions) => {\r\n entry.unsubscribe()\r\n if (cancelOptions?.cancelActive) {\r\n cancelActiveListeners(entry)\r\n }\r\n }\r\n }\r\n\r\n const findListenerEntry = (\r\n comparator: (entry: ListenerEntry) => boolean\r\n ): ListenerEntry | undefined => {\r\n for (const entry of Array.from(listenerMap.values())) {\r\n if (comparator(entry)) {\r\n return entry\r\n }\r\n }\r\n\r\n return undefined\r\n }\r\n\r\n const startListening = (options: FallbackAddListenerOptions) => {\r\n let entry = findListenerEntry(\r\n (existingEntry) => existingEntry.effect === options.effect\r\n )\r\n\r\n if (!entry) {\r\n entry = createListenerEntry(options as any)\r\n }\r\n\r\n return insertEntry(entry)\r\n }\r\n\r\n const stopListening = (\r\n options: FallbackAddListenerOptions & UnsubscribeListenerOptions\r\n ): boolean => {\r\n const { type, effect, predicate } = getListenerEntryPropsFrom(options)\r\n\r\n const entry = findListenerEntry((entry) => {\r\n const matchPredicateOrType =\r\n typeof type === 'string'\r\n ? entry.type === type\r\n : entry.predicate === predicate\r\n\r\n return matchPredicateOrType && entry.effect === effect\r\n })\r\n\r\n if (entry) {\r\n entry.unsubscribe()\r\n if (options.cancelActive) {\r\n cancelActiveListeners(entry)\r\n }\r\n }\r\n\r\n return !!entry\r\n }\r\n\r\n const notifyListener = async (\r\n entry: ListenerEntry>,\r\n action: AnyAction,\r\n api: MiddlewareAPI,\r\n getOriginalState: () => S\r\n ) => {\r\n const internalTaskController = new AbortController()\r\n const take = createTakePattern(\r\n startListening,\r\n internalTaskController.signal\r\n )\r\n const autoJoinPromises: Promise[] = []\r\n\r\n try {\r\n entry.pending.add(internalTaskController)\r\n await Promise.resolve(\r\n entry.effect(\r\n action,\r\n // Use assign() rather than ... to avoid extra helper functions added to bundle\r\n assign({}, api, {\r\n getOriginalState,\r\n condition: (\r\n predicate: AnyListenerPredicate,\r\n timeout?: number\r\n ) => take(predicate, timeout).then(Boolean),\r\n take,\r\n delay: createDelay(internalTaskController.signal),\r\n pause: createPause(internalTaskController.signal),\r\n extra,\r\n signal: internalTaskController.signal,\r\n fork: createFork(internalTaskController.signal, autoJoinPromises),\r\n unsubscribe: entry.unsubscribe,\r\n subscribe: () => {\r\n listenerMap.set(entry.id, entry)\r\n },\r\n cancelActiveListeners: () => {\r\n entry.pending.forEach((controller, _, set) => {\r\n if (controller !== internalTaskController) {\r\n abortControllerWithReason(controller, listenerCancelled)\r\n set.delete(controller)\r\n }\r\n })\r\n },\r\n })\r\n )\r\n )\r\n } catch (listenerError) {\r\n if (!(listenerError instanceof TaskAbortError)) {\r\n safelyNotifyError(onError, listenerError, {\r\n raisedBy: 'effect',\r\n })\r\n }\r\n } finally {\r\n await Promise.allSettled(autoJoinPromises)\r\n\r\n abortControllerWithReason(internalTaskController, listenerCompleted) // Notify that the task has completed\r\n entry.pending.delete(internalTaskController)\r\n }\r\n }\r\n\r\n const clearListenerMiddleware = createClearListenerMiddleware(listenerMap)\r\n\r\n const middleware: ListenerMiddleware =\r\n (api) => (next) => (action) => {\r\n if (!isAction(action)) {\r\n // we only want to notify listeners for action objects\r\n return next(action)\r\n }\r\n\r\n if (addListener.match(action)) {\r\n return startListening(action.payload)\r\n }\r\n\r\n if (clearAllListeners.match(action)) {\r\n clearListenerMiddleware()\r\n return\r\n }\r\n\r\n if (removeListener.match(action)) {\r\n return stopListening(action.payload)\r\n }\r\n\r\n // Need to get this state _before_ the reducer processes the action\r\n let originalState: S | typeof INTERNAL_NIL_TOKEN = api.getState()\r\n\r\n // `getOriginalState` can only be called synchronously.\r\n // @see https://github.com/reduxjs/redux-toolkit/discussions/1648#discussioncomment-1932820\r\n const getOriginalState = (): S => {\r\n if (originalState === INTERNAL_NIL_TOKEN) {\r\n throw new Error(\r\n `${alm}: getOriginalState can only be called synchronously`\r\n )\r\n }\r\n\r\n return originalState as S\r\n }\r\n\r\n let result: unknown\r\n\r\n try {\r\n // Actually forward the action to the reducer before we handle listeners\r\n result = next(action)\r\n\r\n if (listenerMap.size > 0) {\r\n let currentState = api.getState()\r\n // Work around ESBuild+TS transpilation issue\r\n const listenerEntries = Array.from(listenerMap.values())\r\n for (let entry of listenerEntries) {\r\n let runListener = false\r\n\r\n try {\r\n runListener = entry.predicate(action, currentState, originalState)\r\n } catch (predicateError) {\r\n runListener = false\r\n\r\n safelyNotifyError(onError, predicateError, {\r\n raisedBy: 'predicate',\r\n })\r\n }\r\n\r\n if (!runListener) {\r\n continue\r\n }\r\n\r\n notifyListener(entry, action, api, getOriginalState)\r\n }\r\n }\r\n } finally {\r\n // Remove `originalState` store from this scope.\r\n originalState = INTERNAL_NIL_TOKEN\r\n }\r\n\r\n return result\r\n }\r\n\r\n return {\r\n middleware,\r\n startListening,\r\n stopListening,\r\n clearListeners: clearListenerMiddleware,\r\n } as ListenerMiddlewareInstance\r\n}\r\n", "import type { StoreEnhancer } from 'redux'\r\n\r\nexport const SHOULD_AUTOBATCH = 'RTK_autoBatch'\r\n\r\nexport const prepareAutoBatched =\r\n () =>\r\n (payload: T): { payload: T; meta: unknown } => ({\r\n payload,\r\n meta: { [SHOULD_AUTOBATCH]: true },\r\n })\r\n\r\n// TODO Remove this in 2.0\r\n// Copied from https://github.com/feross/queue-microtask\r\nlet promise: Promise\r\nconst queueMicrotaskShim =\r\n typeof queueMicrotask === 'function'\r\n ? queueMicrotask.bind(\r\n typeof window !== 'undefined'\r\n ? window\r\n : typeof global !== 'undefined'\r\n ? global\r\n : globalThis\r\n )\r\n : // reuse resolved promise, and allocate it lazily\r\n (cb: () => void) =>\r\n (promise || (promise = Promise.resolve())).then(cb).catch((err: any) =>\r\n setTimeout(() => {\r\n throw err\r\n }, 0)\r\n )\r\n\r\nconst createQueueWithTimer = (timeout: number) => {\r\n return (notify: () => void) => {\r\n setTimeout(notify, timeout)\r\n }\r\n}\r\n\r\n// requestAnimationFrame won't exist in SSR environments.\r\n// Fall back to a vague approximation just to keep from erroring.\r\nconst rAF =\r\n typeof window !== 'undefined' && window.requestAnimationFrame\r\n ? window.requestAnimationFrame\r\n : createQueueWithTimer(10)\r\n\r\nexport type AutoBatchOptions =\r\n | { type: 'tick' }\r\n | { type: 'timer'; timeout: number }\r\n | { type: 'raf' }\r\n | { type: 'callback'; queueNotification: (notify: () => void) => void }\r\n\r\n/**\r\n * A Redux store enhancer that watches for \"low-priority\" actions, and delays\r\n * notifying subscribers until either the queued callback executes or the\r\n * next \"standard-priority\" action is dispatched.\r\n *\r\n * This allows dispatching multiple \"low-priority\" actions in a row with only\r\n * a single subscriber notification to the UI after the sequence of actions\r\n * is finished, thus improving UI re-render performance.\r\n *\r\n * Watches for actions with the `action.meta[SHOULD_AUTOBATCH]` attribute.\r\n * This can be added to `action.meta` manually, or by using the\r\n * `prepareAutoBatched` helper.\r\n *\r\n * By default, it will queue a notification for the end of the event loop tick.\r\n * However, you can pass several other options to configure the behavior:\r\n * - `{type: 'tick'}: queues using `queueMicrotask` (default)\r\n * - `{type: 'timer, timeout: number}`: queues using `setTimeout`\r\n * - `{type: 'raf'}`: queues using `requestAnimationFrame`\r\n * - `{type: 'callback', queueNotification: (notify: () => void) => void}: lets you provide your own callback\r\n *\r\n *\r\n */\r\nexport const autoBatchEnhancer =\r\n (options: AutoBatchOptions = { type: 'raf' }): StoreEnhancer =>\r\n (next) =>\r\n (...args) => {\r\n const store = next(...args)\r\n\r\n let notifying = true\r\n let shouldNotifyAtEndOfTick = false\r\n let notificationQueued = false\r\n\r\n const listeners = new Set<() => void>()\r\n\r\n const queueCallback =\r\n options.type === 'tick'\r\n ? queueMicrotaskShim\r\n : options.type === 'raf'\r\n ? rAF\r\n : options.type === 'callback'\r\n ? options.queueNotification\r\n : createQueueWithTimer(options.timeout)\r\n\r\n const notifyListeners = () => {\r\n // We're running at the end of the event loop tick.\r\n // Run the real listener callbacks to actually update the UI.\r\n notificationQueued = false\r\n if (shouldNotifyAtEndOfTick) {\r\n shouldNotifyAtEndOfTick = false\r\n listeners.forEach((l) => l())\r\n }\r\n }\r\n\r\n return Object.assign({}, store, {\r\n // Override the base `store.subscribe` method to keep original listeners\r\n // from running if we're delaying notifications\r\n subscribe(listener: () => void) {\r\n // Each wrapped listener will only call the real listener if\r\n // the `notifying` flag is currently active when it's called.\r\n // This lets the base store work as normal, while the actual UI\r\n // update becomes controlled by this enhancer.\r\n const wrappedListener: typeof listener = () => notifying && listener()\r\n const unsubscribe = store.subscribe(wrappedListener)\r\n listeners.add(listener)\r\n return () => {\r\n unsubscribe()\r\n listeners.delete(listener)\r\n }\r\n },\r\n // Override the base `store.dispatch` method so that we can check actions\r\n // for the `shouldAutoBatch` flag and determine if batching is active\r\n dispatch(action: any) {\r\n try {\r\n // If the action does _not_ have the `shouldAutoBatch` flag,\r\n // we resume/continue normal notify-after-each-dispatch behavior\r\n notifying = !action?.meta?.[SHOULD_AUTOBATCH]\r\n // If a `notifyListeners` microtask was queued, you can't cancel it.\r\n // Instead, we set a flag so that it's a no-op when it does run\r\n shouldNotifyAtEndOfTick = !notifying\r\n if (shouldNotifyAtEndOfTick) {\r\n // We've seen at least 1 action with `SHOULD_AUTOBATCH`. Try to queue\r\n // a microtask to notify listeners at the end of the event loop tick.\r\n // Make sure we only enqueue this _once_ per tick.\r\n if (!notificationQueued) {\r\n notificationQueued = true\r\n queueCallback(notifyListeners)\r\n }\r\n }\r\n // Go ahead and process the action as usual, including reducers.\r\n // If normal notification behavior is enabled, the store will notify\r\n // all of its own listeners, and the wrapper callbacks above will\r\n // see `notifying` is true and pass on to the real listener callbacks.\r\n // If we're \"batching\" behavior, then the wrapped callbacks will\r\n // bail out, causing the base store notification behavior to be no-ops.\r\n return store.dispatch(action)\r\n } finally {\r\n // Assume we're back to normal behavior after each action\r\n notifying = true\r\n }\r\n },\r\n })\r\n }\r\n", "var __extends = (this && this.__extends) || (function () {\r\n var extendStatics = function (d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n };\r\n return function (d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n };\r\n})();\r\nvar __generator = (this && this.__generator) || function (thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\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;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n};\r\nvar __spreadArray = (this && this.__spreadArray) || function (to, from) {\r\n for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)\r\n to[j] = from[i];\r\n return to;\r\n};\r\nvar __defProp = Object.defineProperty;\r\nvar __defProps = Object.defineProperties;\r\nvar __getOwnPropDescs = Object.getOwnPropertyDescriptors;\r\nvar __getOwnPropSymbols = Object.getOwnPropertySymbols;\r\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\r\nvar __propIsEnum = Object.prototype.propertyIsEnumerable;\r\nvar __defNormalProp = function (obj, key, value) { return key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value: value }) : obj[key] = value; };\r\nvar __spreadValues = function (a, b) {\r\n for (var prop in b || (b = {}))\r\n if (__hasOwnProp.call(b, prop))\r\n __defNormalProp(a, prop, b[prop]);\r\n if (__getOwnPropSymbols)\r\n for (var _i = 0, _c = __getOwnPropSymbols(b); _i < _c.length; _i++) {\r\n var prop = _c[_i];\r\n if (__propIsEnum.call(b, prop))\r\n __defNormalProp(a, prop, b[prop]);\r\n }\r\n return a;\r\n};\r\nvar __spreadProps = function (a, b) { return __defProps(a, __getOwnPropDescs(b)); };\r\nvar __async = function (__this, __arguments, generator) {\r\n return new Promise(function (resolve, reject) {\r\n var fulfilled = function (value) {\r\n try {\r\n step(generator.next(value));\r\n }\r\n catch (e) {\r\n reject(e);\r\n }\r\n };\r\n var rejected = function (value) {\r\n try {\r\n step(generator.throw(value));\r\n }\r\n catch (e) {\r\n reject(e);\r\n }\r\n };\r\n var step = function (x) { return x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); };\r\n step((generator = generator.apply(__this, __arguments)).next());\r\n });\r\n};\r\n// src/index.ts\r\nimport { enableES5 } from \"immer\";\r\nexport * from \"redux\";\r\nimport { default as default2, current as current2, freeze, original, isDraft as isDraft4 } from \"immer\";\r\nimport { createSelector as createSelector2 } from \"reselect\";\r\n// src/createDraftSafeSelector.ts\r\nimport { current, isDraft } from \"immer\";\r\nimport { createSelector } from \"reselect\";\r\nvar createDraftSafeSelector = function () {\r\n var args = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n args[_i] = arguments[_i];\r\n }\r\n var selector = createSelector.apply(void 0, args);\r\n var wrappedSelector = function (value) {\r\n var rest = [];\r\n for (var _i = 1; _i < arguments.length; _i++) {\r\n rest[_i - 1] = arguments[_i];\r\n }\r\n return selector.apply(void 0, __spreadArray([isDraft(value) ? current(value) : value], rest));\r\n };\r\n return wrappedSelector;\r\n};\r\n// src/configureStore.ts\r\nimport { createStore, compose as compose2, applyMiddleware, combineReducers } from \"redux\";\r\n// src/devtoolsExtension.ts\r\nimport { compose } from \"redux\";\r\nvar composeWithDevTools = typeof window !== \"undefined\" && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ : function () {\r\n if (arguments.length === 0)\r\n return void 0;\r\n if (typeof arguments[0] === \"object\")\r\n return compose;\r\n return compose.apply(null, arguments);\r\n};\r\nvar devToolsEnhancer = typeof window !== \"undefined\" && window.__REDUX_DEVTOOLS_EXTENSION__ ? window.__REDUX_DEVTOOLS_EXTENSION__ : function () {\r\n return function (noop2) {\r\n return noop2;\r\n };\r\n};\r\n// src/isPlainObject.ts\r\nfunction isPlainObject(value) {\r\n if (typeof value !== \"object\" || value === null)\r\n return false;\r\n var proto = Object.getPrototypeOf(value);\r\n if (proto === null)\r\n return true;\r\n var baseProto = proto;\r\n while (Object.getPrototypeOf(baseProto) !== null) {\r\n baseProto = Object.getPrototypeOf(baseProto);\r\n }\r\n return proto === baseProto;\r\n}\r\n// src/getDefaultMiddleware.ts\r\nimport thunkMiddleware from \"redux-thunk\";\r\n// src/tsHelpers.ts\r\nvar hasMatchFunction = function (v) {\r\n return v && typeof v.match === \"function\";\r\n};\r\n// src/createAction.ts\r\nfunction createAction(type, prepareAction) {\r\n function actionCreator() {\r\n var args = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n args[_i] = arguments[_i];\r\n }\r\n if (prepareAction) {\r\n var prepared = prepareAction.apply(void 0, args);\r\n if (!prepared) {\r\n throw new Error(\"prepareAction did not return an object\");\r\n }\r\n return __spreadValues(__spreadValues({\r\n type: type,\r\n payload: prepared.payload\r\n }, \"meta\" in prepared && { meta: prepared.meta }), \"error\" in prepared && { error: prepared.error });\r\n }\r\n return { type: type, payload: args[0] };\r\n }\r\n actionCreator.toString = function () { return \"\" + type; };\r\n actionCreator.type = type;\r\n actionCreator.match = function (action) { return action.type === type; };\r\n return actionCreator;\r\n}\r\nfunction isAction(action) {\r\n return isPlainObject(action) && \"type\" in action;\r\n}\r\nfunction isActionCreator(action) {\r\n return typeof action === \"function\" && \"type\" in action && hasMatchFunction(action);\r\n}\r\nfunction isFSA(action) {\r\n return isAction(action) && typeof action.type === \"string\" && Object.keys(action).every(isValidKey);\r\n}\r\nfunction isValidKey(key) {\r\n return [\"type\", \"payload\", \"error\", \"meta\"].indexOf(key) > -1;\r\n}\r\nfunction getType(actionCreator) {\r\n return \"\" + actionCreator;\r\n}\r\n// src/actionCreatorInvariantMiddleware.ts\r\nfunction getMessage(type) {\r\n var splitType = type ? (\"\" + type).split(\"/\") : [];\r\n var actionName = splitType[splitType.length - 1] || \"actionCreator\";\r\n return \"Detected an action creator with type \\\"\" + (type || \"unknown\") + \"\\\" being dispatched. \\nMake sure you're calling the action creator before dispatching, i.e. `dispatch(\" + actionName + \"())` instead of `dispatch(\" + actionName + \")`. This is necessary even if the action has no payload.\";\r\n}\r\nfunction createActionCreatorInvariantMiddleware(options) {\r\n if (options === void 0) { options = {}; }\r\n if (process.env.NODE_ENV === \"production\") {\r\n return function () { return function (next) { return function (action) { return next(action); }; }; };\r\n }\r\n var _c = options.isActionCreator, isActionCreator2 = _c === void 0 ? isActionCreator : _c;\r\n return function () { return function (next) { return function (action) {\r\n if (isActionCreator2(action)) {\r\n console.warn(getMessage(action.type));\r\n }\r\n return next(action);\r\n }; }; };\r\n}\r\n// src/utils.ts\r\nimport createNextState, { isDraftable } from \"immer\";\r\nfunction getTimeMeasureUtils(maxDelay, fnName) {\r\n var elapsed = 0;\r\n return {\r\n measureTime: function (fn) {\r\n var started = Date.now();\r\n try {\r\n return fn();\r\n }\r\n finally {\r\n var finished = Date.now();\r\n elapsed += finished - started;\r\n }\r\n },\r\n warnIfExceeded: function () {\r\n if (elapsed > maxDelay) {\r\n console.warn(fnName + \" took \" + elapsed + \"ms, which is more than the warning threshold of \" + maxDelay + \"ms. \\nIf your state or actions are very large, you may want to disable the middleware as it might cause too much of a slowdown in development mode. See https://redux-toolkit.js.org/api/getDefaultMiddleware for instructions.\\nIt is disabled in production builds, so you don't need to worry about that.\");\r\n }\r\n }\r\n };\r\n}\r\nvar MiddlewareArray = /** @class */ (function (_super) {\r\n __extends(MiddlewareArray, _super);\r\n function MiddlewareArray() {\r\n var args = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n args[_i] = arguments[_i];\r\n }\r\n var _this = _super.apply(this, args) || this;\r\n Object.setPrototypeOf(_this, MiddlewareArray.prototype);\r\n return _this;\r\n }\r\n Object.defineProperty(MiddlewareArray, Symbol.species, {\r\n get: function () {\r\n return MiddlewareArray;\r\n },\r\n enumerable: false,\r\n configurable: true\r\n });\r\n MiddlewareArray.prototype.concat = function () {\r\n var arr = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n arr[_i] = arguments[_i];\r\n }\r\n return _super.prototype.concat.apply(this, arr);\r\n };\r\n MiddlewareArray.prototype.prepend = function () {\r\n var arr = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n arr[_i] = arguments[_i];\r\n }\r\n if (arr.length === 1 && Array.isArray(arr[0])) {\r\n return new (MiddlewareArray.bind.apply(MiddlewareArray, __spreadArray([void 0], arr[0].concat(this))))();\r\n }\r\n return new (MiddlewareArray.bind.apply(MiddlewareArray, __spreadArray([void 0], arr.concat(this))))();\r\n };\r\n return MiddlewareArray;\r\n}(Array));\r\nvar EnhancerArray = /** @class */ (function (_super) {\r\n __extends(EnhancerArray, _super);\r\n function EnhancerArray() {\r\n var args = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n args[_i] = arguments[_i];\r\n }\r\n var _this = _super.apply(this, args) || this;\r\n Object.setPrototypeOf(_this, EnhancerArray.prototype);\r\n return _this;\r\n }\r\n Object.defineProperty(EnhancerArray, Symbol.species, {\r\n get: function () {\r\n return EnhancerArray;\r\n },\r\n enumerable: false,\r\n configurable: true\r\n });\r\n EnhancerArray.prototype.concat = function () {\r\n var arr = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n arr[_i] = arguments[_i];\r\n }\r\n return _super.prototype.concat.apply(this, arr);\r\n };\r\n EnhancerArray.prototype.prepend = function () {\r\n var arr = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n arr[_i] = arguments[_i];\r\n }\r\n if (arr.length === 1 && Array.isArray(arr[0])) {\r\n return new (EnhancerArray.bind.apply(EnhancerArray, __spreadArray([void 0], arr[0].concat(this))))();\r\n }\r\n return new (EnhancerArray.bind.apply(EnhancerArray, __spreadArray([void 0], arr.concat(this))))();\r\n };\r\n return EnhancerArray;\r\n}(Array));\r\nfunction freezeDraftable(val) {\r\n return isDraftable(val) ? createNextState(val, function () {\r\n }) : val;\r\n}\r\n// src/immutableStateInvariantMiddleware.ts\r\nvar isProduction = process.env.NODE_ENV === \"production\";\r\nvar prefix = \"Invariant failed\";\r\nfunction invariant(condition, message) {\r\n if (condition) {\r\n return;\r\n }\r\n if (isProduction) {\r\n throw new Error(prefix);\r\n }\r\n throw new Error(prefix + \": \" + (message || \"\"));\r\n}\r\nfunction stringify(obj, serializer, indent, decycler) {\r\n return JSON.stringify(obj, getSerialize(serializer, decycler), indent);\r\n}\r\nfunction getSerialize(serializer, decycler) {\r\n var stack = [], keys = [];\r\n if (!decycler)\r\n decycler = function (_, value) {\r\n if (stack[0] === value)\r\n return \"[Circular ~]\";\r\n return \"[Circular ~.\" + keys.slice(0, stack.indexOf(value)).join(\".\") + \"]\";\r\n };\r\n return function (key, value) {\r\n if (stack.length > 0) {\r\n var thisPos = stack.indexOf(this);\r\n ~thisPos ? stack.splice(thisPos + 1) : stack.push(this);\r\n ~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key);\r\n if (~stack.indexOf(value))\r\n value = decycler.call(this, key, value);\r\n }\r\n else\r\n stack.push(value);\r\n return serializer == null ? value : serializer.call(this, key, value);\r\n };\r\n}\r\nfunction isImmutableDefault(value) {\r\n return typeof value !== \"object\" || value == null || Object.isFrozen(value);\r\n}\r\nfunction trackForMutations(isImmutable, ignorePaths, obj) {\r\n var trackedProperties = trackProperties(isImmutable, ignorePaths, obj);\r\n return {\r\n detectMutations: function () {\r\n return detectMutations(isImmutable, ignorePaths, trackedProperties, obj);\r\n }\r\n };\r\n}\r\nfunction trackProperties(isImmutable, ignorePaths, obj, path, checkedObjects) {\r\n if (ignorePaths === void 0) { ignorePaths = []; }\r\n if (path === void 0) { path = \"\"; }\r\n if (checkedObjects === void 0) { checkedObjects = new Set(); }\r\n var tracked = { value: obj };\r\n if (!isImmutable(obj) && !checkedObjects.has(obj)) {\r\n checkedObjects.add(obj);\r\n tracked.children = {};\r\n for (var key in obj) {\r\n var childPath = path ? path + \".\" + key : key;\r\n if (ignorePaths.length && ignorePaths.indexOf(childPath) !== -1) {\r\n continue;\r\n }\r\n tracked.children[key] = trackProperties(isImmutable, ignorePaths, obj[key], childPath);\r\n }\r\n }\r\n return tracked;\r\n}\r\nfunction detectMutations(isImmutable, ignoredPaths, trackedProperty, obj, sameParentRef, path) {\r\n if (ignoredPaths === void 0) { ignoredPaths = []; }\r\n if (sameParentRef === void 0) { sameParentRef = false; }\r\n if (path === void 0) { path = \"\"; }\r\n var prevObj = trackedProperty ? trackedProperty.value : void 0;\r\n var sameRef = prevObj === obj;\r\n if (sameParentRef && !sameRef && !Number.isNaN(obj)) {\r\n return { wasMutated: true, path: path };\r\n }\r\n if (isImmutable(prevObj) || isImmutable(obj)) {\r\n return { wasMutated: false };\r\n }\r\n var keysToDetect = {};\r\n for (var key in trackedProperty.children) {\r\n keysToDetect[key] = true;\r\n }\r\n for (var key in obj) {\r\n keysToDetect[key] = true;\r\n }\r\n var hasIgnoredPaths = ignoredPaths.length > 0;\r\n var _loop_1 = function (key) {\r\n var nestedPath = path ? path + \".\" + key : key;\r\n if (hasIgnoredPaths) {\r\n var hasMatches = ignoredPaths.some(function (ignored) {\r\n if (ignored instanceof RegExp) {\r\n return ignored.test(nestedPath);\r\n }\r\n return nestedPath === ignored;\r\n });\r\n if (hasMatches) {\r\n return \"continue\";\r\n }\r\n }\r\n var result = detectMutations(isImmutable, ignoredPaths, trackedProperty.children[key], obj[key], sameRef, nestedPath);\r\n if (result.wasMutated) {\r\n return { value: result };\r\n }\r\n };\r\n for (var key in keysToDetect) {\r\n var state_1 = _loop_1(key);\r\n if (typeof state_1 === \"object\")\r\n return state_1.value;\r\n }\r\n return { wasMutated: false };\r\n}\r\nfunction createImmutableStateInvariantMiddleware(options) {\r\n if (options === void 0) { options = {}; }\r\n if (process.env.NODE_ENV === \"production\") {\r\n return function () { return function (next) { return function (action) { return next(action); }; }; };\r\n }\r\n var _c = options.isImmutable, isImmutable = _c === void 0 ? isImmutableDefault : _c, ignoredPaths = options.ignoredPaths, _d = options.warnAfter, warnAfter = _d === void 0 ? 32 : _d, ignore = options.ignore;\r\n ignoredPaths = ignoredPaths || ignore;\r\n var track = trackForMutations.bind(null, isImmutable, ignoredPaths);\r\n return function (_c) {\r\n var getState = _c.getState;\r\n var state = getState();\r\n var tracker = track(state);\r\n var result;\r\n return function (next) { return function (action) {\r\n var measureUtils = getTimeMeasureUtils(warnAfter, \"ImmutableStateInvariantMiddleware\");\r\n measureUtils.measureTime(function () {\r\n state = getState();\r\n result = tracker.detectMutations();\r\n tracker = track(state);\r\n invariant(!result.wasMutated, \"A state mutation was detected between dispatches, in the path '\" + (result.path || \"\") + \"'. This may cause incorrect behavior. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)\");\r\n });\r\n var dispatchedAction = next(action);\r\n measureUtils.measureTime(function () {\r\n state = getState();\r\n result = tracker.detectMutations();\r\n tracker = track(state);\r\n result.wasMutated && invariant(!result.wasMutated, \"A state mutation was detected inside a dispatch, in the path: \" + (result.path || \"\") + \". Take a look at the reducer(s) handling the action \" + stringify(action) + \". (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)\");\r\n });\r\n measureUtils.warnIfExceeded();\r\n return dispatchedAction;\r\n }; };\r\n };\r\n}\r\n// src/serializableStateInvariantMiddleware.ts\r\nfunction isPlain(val) {\r\n var type = typeof val;\r\n return val == null || type === \"string\" || type === \"boolean\" || type === \"number\" || Array.isArray(val) || isPlainObject(val);\r\n}\r\nfunction findNonSerializableValue(value, path, isSerializable, getEntries, ignoredPaths, cache) {\r\n if (path === void 0) { path = \"\"; }\r\n if (isSerializable === void 0) { isSerializable = isPlain; }\r\n if (ignoredPaths === void 0) { ignoredPaths = []; }\r\n var foundNestedSerializable;\r\n if (!isSerializable(value)) {\r\n return {\r\n keyPath: path || \"\",\r\n value: value\r\n };\r\n }\r\n if (typeof value !== \"object\" || value === null) {\r\n return false;\r\n }\r\n if (cache == null ? void 0 : cache.has(value))\r\n return false;\r\n var entries = getEntries != null ? getEntries(value) : Object.entries(value);\r\n var hasIgnoredPaths = ignoredPaths.length > 0;\r\n var _loop_2 = function (key, nestedValue) {\r\n var nestedPath = path ? path + \".\" + key : key;\r\n if (hasIgnoredPaths) {\r\n var hasMatches = ignoredPaths.some(function (ignored) {\r\n if (ignored instanceof RegExp) {\r\n return ignored.test(nestedPath);\r\n }\r\n return nestedPath === ignored;\r\n });\r\n if (hasMatches) {\r\n return \"continue\";\r\n }\r\n }\r\n if (!isSerializable(nestedValue)) {\r\n return { value: {\r\n keyPath: nestedPath,\r\n value: nestedValue\r\n } };\r\n }\r\n if (typeof nestedValue === \"object\") {\r\n foundNestedSerializable = findNonSerializableValue(nestedValue, nestedPath, isSerializable, getEntries, ignoredPaths, cache);\r\n if (foundNestedSerializable) {\r\n return { value: foundNestedSerializable };\r\n }\r\n }\r\n };\r\n for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {\r\n var _c = entries_1[_i], key = _c[0], nestedValue = _c[1];\r\n var state_2 = _loop_2(key, nestedValue);\r\n if (typeof state_2 === \"object\")\r\n return state_2.value;\r\n }\r\n if (cache && isNestedFrozen(value))\r\n cache.add(value);\r\n return false;\r\n}\r\nfunction isNestedFrozen(value) {\r\n if (!Object.isFrozen(value))\r\n return false;\r\n for (var _i = 0, _c = Object.values(value); _i < _c.length; _i++) {\r\n var nestedValue = _c[_i];\r\n if (typeof nestedValue !== \"object\" || nestedValue === null)\r\n continue;\r\n if (!isNestedFrozen(nestedValue))\r\n return false;\r\n }\r\n return true;\r\n}\r\nfunction createSerializableStateInvariantMiddleware(options) {\r\n if (options === void 0) { options = {}; }\r\n if (process.env.NODE_ENV === \"production\") {\r\n return function () { return function (next) { return function (action) { return next(action); }; }; };\r\n }\r\n var _c = options.isSerializable, isSerializable = _c === void 0 ? isPlain : _c, getEntries = options.getEntries, _d = options.ignoredActions, ignoredActions = _d === void 0 ? [] : _d, _e = options.ignoredActionPaths, ignoredActionPaths = _e === void 0 ? [\"meta.arg\", \"meta.baseQueryMeta\"] : _e, _f = options.ignoredPaths, ignoredPaths = _f === void 0 ? [] : _f, _g = options.warnAfter, warnAfter = _g === void 0 ? 32 : _g, _h = options.ignoreState, ignoreState = _h === void 0 ? false : _h, _j = options.ignoreActions, ignoreActions = _j === void 0 ? false : _j, _k = options.disableCache, disableCache = _k === void 0 ? false : _k;\r\n var cache = !disableCache && WeakSet ? new WeakSet() : void 0;\r\n return function (storeAPI) { return function (next) { return function (action) {\r\n var result = next(action);\r\n var measureUtils = getTimeMeasureUtils(warnAfter, \"SerializableStateInvariantMiddleware\");\r\n if (!ignoreActions && !(ignoredActions.length && ignoredActions.indexOf(action.type) !== -1)) {\r\n measureUtils.measureTime(function () {\r\n var foundActionNonSerializableValue = findNonSerializableValue(action, \"\", isSerializable, getEntries, ignoredActionPaths, cache);\r\n if (foundActionNonSerializableValue) {\r\n var keyPath = foundActionNonSerializableValue.keyPath, value = foundActionNonSerializableValue.value;\r\n console.error(\"A non-serializable value was detected in an action, in the path: `\" + keyPath + \"`. Value:\", value, \"\\nTake a look at the logic that dispatched this action: \", action, \"\\n(See https://redux.js.org/faq/actions#why-should-type-be-a-string-or-at-least-serializable-why-should-my-action-types-be-constants)\", \"\\n(To allow non-serializable values see: https://redux-toolkit.js.org/usage/usage-guide#working-with-non-serializable-data)\");\r\n }\r\n });\r\n }\r\n if (!ignoreState) {\r\n measureUtils.measureTime(function () {\r\n var state = storeAPI.getState();\r\n var foundStateNonSerializableValue = findNonSerializableValue(state, \"\", isSerializable, getEntries, ignoredPaths, cache);\r\n if (foundStateNonSerializableValue) {\r\n var keyPath = foundStateNonSerializableValue.keyPath, value = foundStateNonSerializableValue.value;\r\n console.error(\"A non-serializable value was detected in the state, in the path: `\" + keyPath + \"`. Value:\", value, \"\\nTake a look at the reducer(s) handling this action type: \" + action.type + \".\\n(See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)\");\r\n }\r\n });\r\n measureUtils.warnIfExceeded();\r\n }\r\n return result;\r\n }; }; };\r\n}\r\n// src/getDefaultMiddleware.ts\r\nfunction isBoolean(x) {\r\n return typeof x === \"boolean\";\r\n}\r\nfunction curryGetDefaultMiddleware() {\r\n return function curriedGetDefaultMiddleware(options) {\r\n return getDefaultMiddleware(options);\r\n };\r\n}\r\nfunction getDefaultMiddleware(options) {\r\n if (options === void 0) { options = {}; }\r\n var _c = options.thunk, thunk = _c === void 0 ? true : _c, _d = options.immutableCheck, immutableCheck = _d === void 0 ? true : _d, _e = options.serializableCheck, serializableCheck = _e === void 0 ? true : _e, _f = options.actionCreatorCheck, actionCreatorCheck = _f === void 0 ? true : _f;\r\n var middlewareArray = new MiddlewareArray();\r\n if (thunk) {\r\n if (isBoolean(thunk)) {\r\n middlewareArray.push(thunkMiddleware);\r\n }\r\n else {\r\n middlewareArray.push(thunkMiddleware.withExtraArgument(thunk.extraArgument));\r\n }\r\n }\r\n if (process.env.NODE_ENV !== \"production\") {\r\n if (immutableCheck) {\r\n var immutableOptions = {};\r\n if (!isBoolean(immutableCheck)) {\r\n immutableOptions = immutableCheck;\r\n }\r\n middlewareArray.unshift(createImmutableStateInvariantMiddleware(immutableOptions));\r\n }\r\n if (serializableCheck) {\r\n var serializableOptions = {};\r\n if (!isBoolean(serializableCheck)) {\r\n serializableOptions = serializableCheck;\r\n }\r\n middlewareArray.push(createSerializableStateInvariantMiddleware(serializableOptions));\r\n }\r\n if (actionCreatorCheck) {\r\n var actionCreatorOptions = {};\r\n if (!isBoolean(actionCreatorCheck)) {\r\n actionCreatorOptions = actionCreatorCheck;\r\n }\r\n middlewareArray.unshift(createActionCreatorInvariantMiddleware(actionCreatorOptions));\r\n }\r\n }\r\n return middlewareArray;\r\n}\r\n// src/configureStore.ts\r\nvar IS_PRODUCTION = process.env.NODE_ENV === \"production\";\r\nfunction configureStore(options) {\r\n var curriedGetDefaultMiddleware = curryGetDefaultMiddleware();\r\n var _c = options || {}, _d = _c.reducer, reducer = _d === void 0 ? void 0 : _d, _e = _c.middleware, middleware = _e === void 0 ? curriedGetDefaultMiddleware() : _e, _f = _c.devTools, devTools = _f === void 0 ? true : _f, _g = _c.preloadedState, preloadedState = _g === void 0 ? void 0 : _g, _h = _c.enhancers, enhancers = _h === void 0 ? void 0 : _h;\r\n var rootReducer;\r\n if (typeof reducer === \"function\") {\r\n rootReducer = reducer;\r\n }\r\n else if (isPlainObject(reducer)) {\r\n rootReducer = combineReducers(reducer);\r\n }\r\n else {\r\n throw new Error('\"reducer\" is a required argument, and must be a function or an object of functions that can be passed to combineReducers');\r\n }\r\n var finalMiddleware = middleware;\r\n if (typeof finalMiddleware === \"function\") {\r\n finalMiddleware = finalMiddleware(curriedGetDefaultMiddleware);\r\n if (!IS_PRODUCTION && !Array.isArray(finalMiddleware)) {\r\n throw new Error(\"when using a middleware builder function, an array of middleware must be returned\");\r\n }\r\n }\r\n if (!IS_PRODUCTION && finalMiddleware.some(function (item) { return typeof item !== \"function\"; })) {\r\n throw new Error(\"each middleware provided to configureStore must be a function\");\r\n }\r\n var middlewareEnhancer = applyMiddleware.apply(void 0, finalMiddleware);\r\n var finalCompose = compose2;\r\n if (devTools) {\r\n finalCompose = composeWithDevTools(__spreadValues({\r\n trace: !IS_PRODUCTION\r\n }, typeof devTools === \"object\" && devTools));\r\n }\r\n var defaultEnhancers = new EnhancerArray(middlewareEnhancer);\r\n var storeEnhancers = defaultEnhancers;\r\n if (Array.isArray(enhancers)) {\r\n storeEnhancers = __spreadArray([middlewareEnhancer], enhancers);\r\n }\r\n else if (typeof enhancers === \"function\") {\r\n storeEnhancers = enhancers(defaultEnhancers);\r\n }\r\n var composedEnhancer = finalCompose.apply(void 0, storeEnhancers);\r\n return createStore(rootReducer, preloadedState, composedEnhancer);\r\n}\r\n// src/createReducer.ts\r\nimport createNextState2, { isDraft as isDraft2, isDraftable as isDraftable2 } from \"immer\";\r\n// src/mapBuilders.ts\r\nfunction executeReducerBuilderCallback(builderCallback) {\r\n var actionsMap = {};\r\n var actionMatchers = [];\r\n var defaultCaseReducer;\r\n var builder = {\r\n addCase: function (typeOrActionCreator, reducer) {\r\n if (process.env.NODE_ENV !== \"production\") {\r\n if (actionMatchers.length > 0) {\r\n throw new Error(\"`builder.addCase` should only be called before calling `builder.addMatcher`\");\r\n }\r\n if (defaultCaseReducer) {\r\n throw new Error(\"`builder.addCase` should only be called before calling `builder.addDefaultCase`\");\r\n }\r\n }\r\n var type = typeof typeOrActionCreator === \"string\" ? typeOrActionCreator : typeOrActionCreator.type;\r\n if (!type) {\r\n throw new Error(\"`builder.addCase` cannot be called with an empty action type\");\r\n }\r\n if (type in actionsMap) {\r\n throw new Error(\"`builder.addCase` cannot be called with two reducers for the same action type\");\r\n }\r\n actionsMap[type] = reducer;\r\n return builder;\r\n },\r\n addMatcher: function (matcher, reducer) {\r\n if (process.env.NODE_ENV !== \"production\") {\r\n if (defaultCaseReducer) {\r\n throw new Error(\"`builder.addMatcher` should only be called before calling `builder.addDefaultCase`\");\r\n }\r\n }\r\n actionMatchers.push({ matcher: matcher, reducer: reducer });\r\n return builder;\r\n },\r\n addDefaultCase: function (reducer) {\r\n if (process.env.NODE_ENV !== \"production\") {\r\n if (defaultCaseReducer) {\r\n throw new Error(\"`builder.addDefaultCase` can only be called once\");\r\n }\r\n }\r\n defaultCaseReducer = reducer;\r\n return builder;\r\n }\r\n };\r\n builderCallback(builder);\r\n return [actionsMap, actionMatchers, defaultCaseReducer];\r\n}\r\n// src/createReducer.ts\r\nfunction isStateFunction(x) {\r\n return typeof x === \"function\";\r\n}\r\nvar hasWarnedAboutObjectNotation = false;\r\nfunction createReducer(initialState, mapOrBuilderCallback, actionMatchers, defaultCaseReducer) {\r\n if (actionMatchers === void 0) { actionMatchers = []; }\r\n if (process.env.NODE_ENV !== \"production\") {\r\n if (typeof mapOrBuilderCallback === \"object\") {\r\n if (!hasWarnedAboutObjectNotation) {\r\n hasWarnedAboutObjectNotation = true;\r\n console.warn(\"The object notation for `createReducer` is deprecated, and will be removed in RTK 2.0. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createReducer\");\r\n }\r\n }\r\n }\r\n var _c = typeof mapOrBuilderCallback === \"function\" ? executeReducerBuilderCallback(mapOrBuilderCallback) : [mapOrBuilderCallback, actionMatchers, defaultCaseReducer], actionsMap = _c[0], finalActionMatchers = _c[1], finalDefaultCaseReducer = _c[2];\r\n var getInitialState;\r\n if (isStateFunction(initialState)) {\r\n getInitialState = function () { return freezeDraftable(initialState()); };\r\n }\r\n else {\r\n var frozenInitialState_1 = freezeDraftable(initialState);\r\n getInitialState = function () { return frozenInitialState_1; };\r\n }\r\n function reducer(state, action) {\r\n if (state === void 0) { state = getInitialState(); }\r\n var caseReducers = __spreadArray([\r\n actionsMap[action.type]\r\n ], finalActionMatchers.filter(function (_c) {\r\n var matcher = _c.matcher;\r\n return matcher(action);\r\n }).map(function (_c) {\r\n var reducer2 = _c.reducer;\r\n return reducer2;\r\n }));\r\n if (caseReducers.filter(function (cr) { return !!cr; }).length === 0) {\r\n caseReducers = [finalDefaultCaseReducer];\r\n }\r\n return caseReducers.reduce(function (previousState, caseReducer) {\r\n if (caseReducer) {\r\n if (isDraft2(previousState)) {\r\n var draft = previousState;\r\n var result = caseReducer(draft, action);\r\n if (result === void 0) {\r\n return previousState;\r\n }\r\n return result;\r\n }\r\n else if (!isDraftable2(previousState)) {\r\n var result = caseReducer(previousState, action);\r\n if (result === void 0) {\r\n if (previousState === null) {\r\n return previousState;\r\n }\r\n throw Error(\"A case reducer on a non-draftable value must not return undefined\");\r\n }\r\n return result;\r\n }\r\n else {\r\n return createNextState2(previousState, function (draft) {\r\n return caseReducer(draft, action);\r\n });\r\n }\r\n }\r\n return previousState;\r\n }, state);\r\n }\r\n reducer.getInitialState = getInitialState;\r\n return reducer;\r\n}\r\n// src/createSlice.ts\r\nvar hasWarnedAboutObjectNotation2 = false;\r\nfunction getType2(slice, actionKey) {\r\n return slice + \"/\" + actionKey;\r\n}\r\nfunction createSlice(options) {\r\n var name = options.name;\r\n if (!name) {\r\n throw new Error(\"`name` is a required option for createSlice\");\r\n }\r\n if (typeof process !== \"undefined\" && process.env.NODE_ENV === \"development\") {\r\n if (options.initialState === void 0) {\r\n console.error(\"You must provide an `initialState` value that is not `undefined`. You may have misspelled `initialState`\");\r\n }\r\n }\r\n var initialState = typeof options.initialState == \"function\" ? options.initialState : freezeDraftable(options.initialState);\r\n var reducers = options.reducers || {};\r\n var reducerNames = Object.keys(reducers);\r\n var sliceCaseReducersByName = {};\r\n var sliceCaseReducersByType = {};\r\n var actionCreators = {};\r\n reducerNames.forEach(function (reducerName) {\r\n var maybeReducerWithPrepare = reducers[reducerName];\r\n var type = getType2(name, reducerName);\r\n var caseReducer;\r\n var prepareCallback;\r\n if (\"reducer\" in maybeReducerWithPrepare) {\r\n caseReducer = maybeReducerWithPrepare.reducer;\r\n prepareCallback = maybeReducerWithPrepare.prepare;\r\n }\r\n else {\r\n caseReducer = maybeReducerWithPrepare;\r\n }\r\n sliceCaseReducersByName[reducerName] = caseReducer;\r\n sliceCaseReducersByType[type] = caseReducer;\r\n actionCreators[reducerName] = prepareCallback ? createAction(type, prepareCallback) : createAction(type);\r\n });\r\n function buildReducer() {\r\n if (process.env.NODE_ENV !== \"production\") {\r\n if (typeof options.extraReducers === \"object\") {\r\n if (!hasWarnedAboutObjectNotation2) {\r\n hasWarnedAboutObjectNotation2 = true;\r\n console.warn(\"The object notation for `createSlice.extraReducers` is deprecated, and will be removed in RTK 2.0. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createSlice\");\r\n }\r\n }\r\n }\r\n var _c = typeof options.extraReducers === \"function\" ? executeReducerBuilderCallback(options.extraReducers) : [options.extraReducers], _d = _c[0], extraReducers = _d === void 0 ? {} : _d, _e = _c[1], actionMatchers = _e === void 0 ? [] : _e, _f = _c[2], defaultCaseReducer = _f === void 0 ? void 0 : _f;\r\n var finalCaseReducers = __spreadValues(__spreadValues({}, extraReducers), sliceCaseReducersByType);\r\n return createReducer(initialState, function (builder) {\r\n for (var key in finalCaseReducers) {\r\n builder.addCase(key, finalCaseReducers[key]);\r\n }\r\n for (var _i = 0, actionMatchers_1 = actionMatchers; _i < actionMatchers_1.length; _i++) {\r\n var m = actionMatchers_1[_i];\r\n builder.addMatcher(m.matcher, m.reducer);\r\n }\r\n if (defaultCaseReducer) {\r\n builder.addDefaultCase(defaultCaseReducer);\r\n }\r\n });\r\n }\r\n var _reducer;\r\n return {\r\n name: name,\r\n reducer: function (state, action) {\r\n if (!_reducer)\r\n _reducer = buildReducer();\r\n return _reducer(state, action);\r\n },\r\n actions: actionCreators,\r\n caseReducers: sliceCaseReducersByName,\r\n getInitialState: function () {\r\n if (!_reducer)\r\n _reducer = buildReducer();\r\n return _reducer.getInitialState();\r\n }\r\n };\r\n}\r\n// src/entities/entity_state.ts\r\nfunction getInitialEntityState() {\r\n return {\r\n ids: [],\r\n entities: {}\r\n };\r\n}\r\nfunction createInitialStateFactory() {\r\n function getInitialState(additionalState) {\r\n if (additionalState === void 0) { additionalState = {}; }\r\n return Object.assign(getInitialEntityState(), additionalState);\r\n }\r\n return { getInitialState: getInitialState };\r\n}\r\n// src/entities/state_selectors.ts\r\nfunction createSelectorsFactory() {\r\n function getSelectors(selectState) {\r\n var selectIds = function (state) { return state.ids; };\r\n var selectEntities = function (state) { return state.entities; };\r\n var selectAll = createDraftSafeSelector(selectIds, selectEntities, function (ids, entities) { return ids.map(function (id) { return entities[id]; }); });\r\n var selectId = function (_, id) { return id; };\r\n var selectById = function (entities, id) { return entities[id]; };\r\n var selectTotal = createDraftSafeSelector(selectIds, function (ids) { return ids.length; });\r\n if (!selectState) {\r\n return {\r\n selectIds: selectIds,\r\n selectEntities: selectEntities,\r\n selectAll: selectAll,\r\n selectTotal: selectTotal,\r\n selectById: createDraftSafeSelector(selectEntities, selectId, selectById)\r\n };\r\n }\r\n var selectGlobalizedEntities = createDraftSafeSelector(selectState, selectEntities);\r\n return {\r\n selectIds: createDraftSafeSelector(selectState, selectIds),\r\n selectEntities: selectGlobalizedEntities,\r\n selectAll: createDraftSafeSelector(selectState, selectAll),\r\n selectTotal: createDraftSafeSelector(selectState, selectTotal),\r\n selectById: createDraftSafeSelector(selectGlobalizedEntities, selectId, selectById)\r\n };\r\n }\r\n return { getSelectors: getSelectors };\r\n}\r\n// src/entities/state_adapter.ts\r\nimport createNextState3, { isDraft as isDraft3 } from \"immer\";\r\nfunction createSingleArgumentStateOperator(mutator) {\r\n var operator = createStateOperator(function (_, state) { return mutator(state); });\r\n return function operation(state) {\r\n return operator(state, void 0);\r\n };\r\n}\r\nfunction createStateOperator(mutator) {\r\n return function operation(state, arg) {\r\n function isPayloadActionArgument(arg2) {\r\n return isFSA(arg2);\r\n }\r\n var runMutator = function (draft) {\r\n if (isPayloadActionArgument(arg)) {\r\n mutator(arg.payload, draft);\r\n }\r\n else {\r\n mutator(arg, draft);\r\n }\r\n };\r\n if (isDraft3(state)) {\r\n runMutator(state);\r\n return state;\r\n }\r\n else {\r\n return createNextState3(state, runMutator);\r\n }\r\n };\r\n}\r\n// src/entities/utils.ts\r\nfunction selectIdValue(entity, selectId) {\r\n var key = selectId(entity);\r\n if (process.env.NODE_ENV !== \"production\" && key === void 0) {\r\n console.warn(\"The entity passed to the `selectId` implementation returned undefined.\", \"You should probably provide your own `selectId` implementation.\", \"The entity that was passed:\", entity, \"The `selectId` implementation:\", selectId.toString());\r\n }\r\n return key;\r\n}\r\nfunction ensureEntitiesArray(entities) {\r\n if (!Array.isArray(entities)) {\r\n entities = Object.values(entities);\r\n }\r\n return entities;\r\n}\r\nfunction splitAddedUpdatedEntities(newEntities, selectId, state) {\r\n newEntities = ensureEntitiesArray(newEntities);\r\n var added = [];\r\n var updated = [];\r\n for (var _i = 0, newEntities_1 = newEntities; _i < newEntities_1.length; _i++) {\r\n var entity = newEntities_1[_i];\r\n var id = selectIdValue(entity, selectId);\r\n if (id in state.entities) {\r\n updated.push({ id: id, changes: entity });\r\n }\r\n else {\r\n added.push(entity);\r\n }\r\n }\r\n return [added, updated];\r\n}\r\n// src/entities/unsorted_state_adapter.ts\r\nfunction createUnsortedStateAdapter(selectId) {\r\n function addOneMutably(entity, state) {\r\n var key = selectIdValue(entity, selectId);\r\n if (key in state.entities) {\r\n return;\r\n }\r\n state.ids.push(key);\r\n state.entities[key] = entity;\r\n }\r\n function addManyMutably(newEntities, state) {\r\n newEntities = ensureEntitiesArray(newEntities);\r\n for (var _i = 0, newEntities_2 = newEntities; _i < newEntities_2.length; _i++) {\r\n var entity = newEntities_2[_i];\r\n addOneMutably(entity, state);\r\n }\r\n }\r\n function setOneMutably(entity, state) {\r\n var key = selectIdValue(entity, selectId);\r\n if (!(key in state.entities)) {\r\n state.ids.push(key);\r\n }\r\n state.entities[key] = entity;\r\n }\r\n function setManyMutably(newEntities, state) {\r\n newEntities = ensureEntitiesArray(newEntities);\r\n for (var _i = 0, newEntities_3 = newEntities; _i < newEntities_3.length; _i++) {\r\n var entity = newEntities_3[_i];\r\n setOneMutably(entity, state);\r\n }\r\n }\r\n function setAllMutably(newEntities, state) {\r\n newEntities = ensureEntitiesArray(newEntities);\r\n state.ids = [];\r\n state.entities = {};\r\n addManyMutably(newEntities, state);\r\n }\r\n function removeOneMutably(key, state) {\r\n return removeManyMutably([key], state);\r\n }\r\n function removeManyMutably(keys, state) {\r\n var didMutate = false;\r\n keys.forEach(function (key) {\r\n if (key in state.entities) {\r\n delete state.entities[key];\r\n didMutate = true;\r\n }\r\n });\r\n if (didMutate) {\r\n state.ids = state.ids.filter(function (id) { return id in state.entities; });\r\n }\r\n }\r\n function removeAllMutably(state) {\r\n Object.assign(state, {\r\n ids: [],\r\n entities: {}\r\n });\r\n }\r\n function takeNewKey(keys, update, state) {\r\n var original2 = state.entities[update.id];\r\n var updated = Object.assign({}, original2, update.changes);\r\n var newKey = selectIdValue(updated, selectId);\r\n var hasNewKey = newKey !== update.id;\r\n if (hasNewKey) {\r\n keys[update.id] = newKey;\r\n delete state.entities[update.id];\r\n }\r\n state.entities[newKey] = updated;\r\n return hasNewKey;\r\n }\r\n function updateOneMutably(update, state) {\r\n return updateManyMutably([update], state);\r\n }\r\n function updateManyMutably(updates, state) {\r\n var newKeys = {};\r\n var updatesPerEntity = {};\r\n updates.forEach(function (update) {\r\n if (update.id in state.entities) {\r\n updatesPerEntity[update.id] = {\r\n id: update.id,\r\n changes: __spreadValues(__spreadValues({}, updatesPerEntity[update.id] ? updatesPerEntity[update.id].changes : null), update.changes)\r\n };\r\n }\r\n });\r\n updates = Object.values(updatesPerEntity);\r\n var didMutateEntities = updates.length > 0;\r\n if (didMutateEntities) {\r\n var didMutateIds = updates.filter(function (update) { return takeNewKey(newKeys, update, state); }).length > 0;\r\n if (didMutateIds) {\r\n state.ids = Object.keys(state.entities);\r\n }\r\n }\r\n }\r\n function upsertOneMutably(entity, state) {\r\n return upsertManyMutably([entity], state);\r\n }\r\n function upsertManyMutably(newEntities, state) {\r\n var _c = splitAddedUpdatedEntities(newEntities, selectId, state), added = _c[0], updated = _c[1];\r\n updateManyMutably(updated, state);\r\n addManyMutably(added, state);\r\n }\r\n return {\r\n removeAll: createSingleArgumentStateOperator(removeAllMutably),\r\n addOne: createStateOperator(addOneMutably),\r\n addMany: createStateOperator(addManyMutably),\r\n setOne: createStateOperator(setOneMutably),\r\n setMany: createStateOperator(setManyMutably),\r\n setAll: createStateOperator(setAllMutably),\r\n updateOne: createStateOperator(updateOneMutably),\r\n updateMany: createStateOperator(updateManyMutably),\r\n upsertOne: createStateOperator(upsertOneMutably),\r\n upsertMany: createStateOperator(upsertManyMutably),\r\n removeOne: createStateOperator(removeOneMutably),\r\n removeMany: createStateOperator(removeManyMutably)\r\n };\r\n}\r\n// src/entities/sorted_state_adapter.ts\r\nfunction createSortedStateAdapter(selectId, sort) {\r\n var _c = createUnsortedStateAdapter(selectId), removeOne = _c.removeOne, removeMany = _c.removeMany, removeAll = _c.removeAll;\r\n function addOneMutably(entity, state) {\r\n return addManyMutably([entity], state);\r\n }\r\n function addManyMutably(newEntities, state) {\r\n newEntities = ensureEntitiesArray(newEntities);\r\n var models = newEntities.filter(function (model) { return !(selectIdValue(model, selectId) in state.entities); });\r\n if (models.length !== 0) {\r\n merge(models, state);\r\n }\r\n }\r\n function setOneMutably(entity, state) {\r\n return setManyMutably([entity], state);\r\n }\r\n function setManyMutably(newEntities, state) {\r\n newEntities = ensureEntitiesArray(newEntities);\r\n if (newEntities.length !== 0) {\r\n merge(newEntities, state);\r\n }\r\n }\r\n function setAllMutably(newEntities, state) {\r\n newEntities = ensureEntitiesArray(newEntities);\r\n state.entities = {};\r\n state.ids = [];\r\n addManyMutably(newEntities, state);\r\n }\r\n function updateOneMutably(update, state) {\r\n return updateManyMutably([update], state);\r\n }\r\n function updateManyMutably(updates, state) {\r\n var appliedUpdates = false;\r\n for (var _i = 0, updates_1 = updates; _i < updates_1.length; _i++) {\r\n var update = updates_1[_i];\r\n var entity = state.entities[update.id];\r\n if (!entity) {\r\n continue;\r\n }\r\n appliedUpdates = true;\r\n Object.assign(entity, update.changes);\r\n var newId = selectId(entity);\r\n if (update.id !== newId) {\r\n delete state.entities[update.id];\r\n state.entities[newId] = entity;\r\n }\r\n }\r\n if (appliedUpdates) {\r\n resortEntities(state);\r\n }\r\n }\r\n function upsertOneMutably(entity, state) {\r\n return upsertManyMutably([entity], state);\r\n }\r\n function upsertManyMutably(newEntities, state) {\r\n var _c = splitAddedUpdatedEntities(newEntities, selectId, state), added = _c[0], updated = _c[1];\r\n updateManyMutably(updated, state);\r\n addManyMutably(added, state);\r\n }\r\n function areArraysEqual(a, b) {\r\n if (a.length !== b.length) {\r\n return false;\r\n }\r\n for (var i = 0; i < a.length && i < b.length; i++) {\r\n if (a[i] === b[i]) {\r\n continue;\r\n }\r\n return false;\r\n }\r\n return true;\r\n }\r\n function merge(models, state) {\r\n models.forEach(function (model) {\r\n state.entities[selectId(model)] = model;\r\n });\r\n resortEntities(state);\r\n }\r\n function resortEntities(state) {\r\n var allEntities = Object.values(state.entities);\r\n allEntities.sort(sort);\r\n var newSortedIds = allEntities.map(selectId);\r\n var ids = state.ids;\r\n if (!areArraysEqual(ids, newSortedIds)) {\r\n state.ids = newSortedIds;\r\n }\r\n }\r\n return {\r\n removeOne: removeOne,\r\n removeMany: removeMany,\r\n removeAll: removeAll,\r\n addOne: createStateOperator(addOneMutably),\r\n updateOne: createStateOperator(updateOneMutably),\r\n upsertOne: createStateOperator(upsertOneMutably),\r\n setOne: createStateOperator(setOneMutably),\r\n setMany: createStateOperator(setManyMutably),\r\n setAll: createStateOperator(setAllMutably),\r\n addMany: createStateOperator(addManyMutably),\r\n updateMany: createStateOperator(updateManyMutably),\r\n upsertMany: createStateOperator(upsertManyMutably)\r\n };\r\n}\r\n// src/entities/create_adapter.ts\r\nfunction createEntityAdapter(options) {\r\n if (options === void 0) { options = {}; }\r\n var _c = __spreadValues({\r\n sortComparer: false,\r\n selectId: function (instance) { return instance.id; }\r\n }, options), selectId = _c.selectId, sortComparer = _c.sortComparer;\r\n var stateFactory = createInitialStateFactory();\r\n var selectorsFactory = createSelectorsFactory();\r\n var stateAdapter = sortComparer ? createSortedStateAdapter(selectId, sortComparer) : createUnsortedStateAdapter(selectId);\r\n return __spreadValues(__spreadValues(__spreadValues({\r\n selectId: selectId,\r\n sortComparer: sortComparer\r\n }, stateFactory), selectorsFactory), stateAdapter);\r\n}\r\n// src/nanoid.ts\r\nvar urlAlphabet = \"ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW\";\r\nvar nanoid = function (size) {\r\n if (size === void 0) { size = 21; }\r\n var id = \"\";\r\n var i = size;\r\n while (i--) {\r\n id += urlAlphabet[Math.random() * 64 | 0];\r\n }\r\n return id;\r\n};\r\n// src/createAsyncThunk.ts\r\nvar commonProperties = [\r\n \"name\",\r\n \"message\",\r\n \"stack\",\r\n \"code\"\r\n];\r\nvar RejectWithValue = /** @class */ (function () {\r\n function RejectWithValue(payload, meta) {\r\n this.payload = payload;\r\n this.meta = meta;\r\n }\r\n return RejectWithValue;\r\n}());\r\nvar FulfillWithMeta = /** @class */ (function () {\r\n function FulfillWithMeta(payload, meta) {\r\n this.payload = payload;\r\n this.meta = meta;\r\n }\r\n return FulfillWithMeta;\r\n}());\r\nvar miniSerializeError = function (value) {\r\n if (typeof value === \"object\" && value !== null) {\r\n var simpleError = {};\r\n for (var _i = 0, commonProperties_1 = commonProperties; _i < commonProperties_1.length; _i++) {\r\n var property = commonProperties_1[_i];\r\n if (typeof value[property] === \"string\") {\r\n simpleError[property] = value[property];\r\n }\r\n }\r\n return simpleError;\r\n }\r\n return { message: String(value) };\r\n};\r\nvar createAsyncThunk = (function () {\r\n function createAsyncThunk2(typePrefix, payloadCreator, options) {\r\n var fulfilled = createAction(typePrefix + \"/fulfilled\", function (payload, requestId, arg, meta) { return ({\r\n payload: payload,\r\n meta: __spreadProps(__spreadValues({}, meta || {}), {\r\n arg: arg,\r\n requestId: requestId,\r\n requestStatus: \"fulfilled\"\r\n })\r\n }); });\r\n var pending = createAction(typePrefix + \"/pending\", function (requestId, arg, meta) { return ({\r\n payload: void 0,\r\n meta: __spreadProps(__spreadValues({}, meta || {}), {\r\n arg: arg,\r\n requestId: requestId,\r\n requestStatus: \"pending\"\r\n })\r\n }); });\r\n var rejected = createAction(typePrefix + \"/rejected\", function (error, requestId, arg, payload, meta) { return ({\r\n payload: payload,\r\n error: (options && options.serializeError || miniSerializeError)(error || \"Rejected\"),\r\n meta: __spreadProps(__spreadValues({}, meta || {}), {\r\n arg: arg,\r\n requestId: requestId,\r\n rejectedWithValue: !!payload,\r\n requestStatus: \"rejected\",\r\n aborted: (error == null ? void 0 : error.name) === \"AbortError\",\r\n condition: (error == null ? void 0 : error.name) === \"ConditionError\"\r\n })\r\n }); });\r\n var displayedWarning = false;\r\n var AC = typeof AbortController !== \"undefined\" ? AbortController : /** @class */ (function () {\r\n function class_1() {\r\n this.signal = {\r\n aborted: false,\r\n addEventListener: function () {\r\n },\r\n dispatchEvent: function () {\r\n return false;\r\n },\r\n onabort: function () {\r\n },\r\n removeEventListener: function () {\r\n },\r\n reason: void 0,\r\n throwIfAborted: function () {\r\n }\r\n };\r\n }\r\n class_1.prototype.abort = function () {\r\n if (process.env.NODE_ENV !== \"production\") {\r\n if (!displayedWarning) {\r\n displayedWarning = true;\r\n console.info(\"This platform does not implement AbortController. \\nIf you want to use the AbortController to react to `abort` events, please consider importing a polyfill like 'abortcontroller-polyfill/dist/abortcontroller-polyfill-only'.\");\r\n }\r\n }\r\n };\r\n return class_1;\r\n }());\r\n function actionCreator(arg) {\r\n return function (dispatch, getState, extra) {\r\n var requestId = (options == null ? void 0 : options.idGenerator) ? options.idGenerator(arg) : nanoid();\r\n var abortController = new AC();\r\n var abortReason;\r\n var started = false;\r\n function abort(reason) {\r\n abortReason = reason;\r\n abortController.abort();\r\n }\r\n var promise2 = function () {\r\n return __async(this, null, function () {\r\n var _a, _b, finalAction, conditionResult, abortedPromise, err_1, skipDispatch;\r\n return __generator(this, function (_c) {\r\n switch (_c.label) {\r\n case 0:\r\n _c.trys.push([0, 4, , 5]);\r\n conditionResult = (_a = options == null ? void 0 : options.condition) == null ? void 0 : _a.call(options, arg, { getState: getState, extra: extra });\r\n if (!isThenable(conditionResult)) return [3 /*break*/, 2];\r\n return [4 /*yield*/, conditionResult];\r\n case 1:\r\n conditionResult = _c.sent();\r\n _c.label = 2;\r\n case 2:\r\n if (conditionResult === false || abortController.signal.aborted) {\r\n throw {\r\n name: \"ConditionError\",\r\n message: \"Aborted due to condition callback returning false.\"\r\n };\r\n }\r\n started = true;\r\n abortedPromise = new Promise(function (_, reject) { return abortController.signal.addEventListener(\"abort\", function () { return reject({\r\n name: \"AbortError\",\r\n message: abortReason || \"Aborted\"\r\n }); }); });\r\n dispatch(pending(requestId, arg, (_b = options == null ? void 0 : options.getPendingMeta) == null ? void 0 : _b.call(options, { requestId: requestId, arg: arg }, { getState: getState, extra: extra })));\r\n return [4 /*yield*/, Promise.race([\r\n abortedPromise,\r\n Promise.resolve(payloadCreator(arg, {\r\n dispatch: dispatch,\r\n getState: getState,\r\n extra: extra,\r\n requestId: requestId,\r\n signal: abortController.signal,\r\n abort: abort,\r\n rejectWithValue: function (value, meta) {\r\n return new RejectWithValue(value, meta);\r\n },\r\n fulfillWithValue: function (value, meta) {\r\n return new FulfillWithMeta(value, meta);\r\n }\r\n })).then(function (result) {\r\n if (result instanceof RejectWithValue) {\r\n throw result;\r\n }\r\n if (result instanceof FulfillWithMeta) {\r\n return fulfilled(result.payload, requestId, arg, result.meta);\r\n }\r\n return fulfilled(result, requestId, arg);\r\n })\r\n ])];\r\n case 3:\r\n finalAction = _c.sent();\r\n return [3 /*break*/, 5];\r\n case 4:\r\n err_1 = _c.sent();\r\n finalAction = err_1 instanceof RejectWithValue ? rejected(null, requestId, arg, err_1.payload, err_1.meta) : rejected(err_1, requestId, arg);\r\n return [3 /*break*/, 5];\r\n case 5:\r\n skipDispatch = options && !options.dispatchConditionRejection && rejected.match(finalAction) && finalAction.meta.condition;\r\n if (!skipDispatch) {\r\n dispatch(finalAction);\r\n }\r\n return [2 /*return*/, finalAction];\r\n }\r\n });\r\n });\r\n }();\r\n return Object.assign(promise2, {\r\n abort: abort,\r\n requestId: requestId,\r\n arg: arg,\r\n unwrap: function () {\r\n return promise2.then(unwrapResult);\r\n }\r\n });\r\n };\r\n }\r\n return Object.assign(actionCreator, {\r\n pending: pending,\r\n rejected: rejected,\r\n fulfilled: fulfilled,\r\n typePrefix: typePrefix\r\n });\r\n }\r\n createAsyncThunk2.withTypes = function () { return createAsyncThunk2; };\r\n return createAsyncThunk2;\r\n})();\r\nfunction unwrapResult(action) {\r\n if (action.meta && action.meta.rejectedWithValue) {\r\n throw action.payload;\r\n }\r\n if (action.error) {\r\n throw action.error;\r\n }\r\n return action.payload;\r\n}\r\nfunction isThenable(value) {\r\n return value !== null && typeof value === \"object\" && typeof value.then === \"function\";\r\n}\r\n// src/matchers.ts\r\nvar matches = function (matcher, action) {\r\n if (hasMatchFunction(matcher)) {\r\n return matcher.match(action);\r\n }\r\n else {\r\n return matcher(action);\r\n }\r\n};\r\nfunction isAnyOf() {\r\n var matchers = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n matchers[_i] = arguments[_i];\r\n }\r\n return function (action) {\r\n return matchers.some(function (matcher) { return matches(matcher, action); });\r\n };\r\n}\r\nfunction isAllOf() {\r\n var matchers = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n matchers[_i] = arguments[_i];\r\n }\r\n return function (action) {\r\n return matchers.every(function (matcher) { return matches(matcher, action); });\r\n };\r\n}\r\nfunction hasExpectedRequestMetadata(action, validStatus) {\r\n if (!action || !action.meta)\r\n return false;\r\n var hasValidRequestId = typeof action.meta.requestId === \"string\";\r\n var hasValidRequestStatus = validStatus.indexOf(action.meta.requestStatus) > -1;\r\n return hasValidRequestId && hasValidRequestStatus;\r\n}\r\nfunction isAsyncThunkArray(a) {\r\n return typeof a[0] === \"function\" && \"pending\" in a[0] && \"fulfilled\" in a[0] && \"rejected\" in a[0];\r\n}\r\nfunction isPending() {\r\n var asyncThunks = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n asyncThunks[_i] = arguments[_i];\r\n }\r\n if (asyncThunks.length === 0) {\r\n return function (action) { return hasExpectedRequestMetadata(action, [\"pending\"]); };\r\n }\r\n if (!isAsyncThunkArray(asyncThunks)) {\r\n return isPending()(asyncThunks[0]);\r\n }\r\n return function (action) {\r\n var matchers = asyncThunks.map(function (asyncThunk) { return asyncThunk.pending; });\r\n var combinedMatcher = isAnyOf.apply(void 0, matchers);\r\n return combinedMatcher(action);\r\n };\r\n}\r\nfunction isRejected() {\r\n var asyncThunks = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n asyncThunks[_i] = arguments[_i];\r\n }\r\n if (asyncThunks.length === 0) {\r\n return function (action) { return hasExpectedRequestMetadata(action, [\"rejected\"]); };\r\n }\r\n if (!isAsyncThunkArray(asyncThunks)) {\r\n return isRejected()(asyncThunks[0]);\r\n }\r\n return function (action) {\r\n var matchers = asyncThunks.map(function (asyncThunk) { return asyncThunk.rejected; });\r\n var combinedMatcher = isAnyOf.apply(void 0, matchers);\r\n return combinedMatcher(action);\r\n };\r\n}\r\nfunction isRejectedWithValue() {\r\n var asyncThunks = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n asyncThunks[_i] = arguments[_i];\r\n }\r\n var hasFlag = function (action) {\r\n return action && action.meta && action.meta.rejectedWithValue;\r\n };\r\n if (asyncThunks.length === 0) {\r\n return function (action) {\r\n var combinedMatcher = isAllOf(isRejected.apply(void 0, asyncThunks), hasFlag);\r\n return combinedMatcher(action);\r\n };\r\n }\r\n if (!isAsyncThunkArray(asyncThunks)) {\r\n return isRejectedWithValue()(asyncThunks[0]);\r\n }\r\n return function (action) {\r\n var combinedMatcher = isAllOf(isRejected.apply(void 0, asyncThunks), hasFlag);\r\n return combinedMatcher(action);\r\n };\r\n}\r\nfunction isFulfilled() {\r\n var asyncThunks = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n asyncThunks[_i] = arguments[_i];\r\n }\r\n if (asyncThunks.length === 0) {\r\n return function (action) { return hasExpectedRequestMetadata(action, [\"fulfilled\"]); };\r\n }\r\n if (!isAsyncThunkArray(asyncThunks)) {\r\n return isFulfilled()(asyncThunks[0]);\r\n }\r\n return function (action) {\r\n var matchers = asyncThunks.map(function (asyncThunk) { return asyncThunk.fulfilled; });\r\n var combinedMatcher = isAnyOf.apply(void 0, matchers);\r\n return combinedMatcher(action);\r\n };\r\n}\r\nfunction isAsyncThunkAction() {\r\n var asyncThunks = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n asyncThunks[_i] = arguments[_i];\r\n }\r\n if (asyncThunks.length === 0) {\r\n return function (action) { return hasExpectedRequestMetadata(action, [\"pending\", \"fulfilled\", \"rejected\"]); };\r\n }\r\n if (!isAsyncThunkArray(asyncThunks)) {\r\n return isAsyncThunkAction()(asyncThunks[0]);\r\n }\r\n return function (action) {\r\n var matchers = [];\r\n for (var _i = 0, asyncThunks_1 = asyncThunks; _i < asyncThunks_1.length; _i++) {\r\n var asyncThunk = asyncThunks_1[_i];\r\n matchers.push(asyncThunk.pending, asyncThunk.rejected, asyncThunk.fulfilled);\r\n }\r\n var combinedMatcher = isAnyOf.apply(void 0, matchers);\r\n return combinedMatcher(action);\r\n };\r\n}\r\n// src/listenerMiddleware/utils.ts\r\nvar assertFunction = function (func, expected) {\r\n if (typeof func !== \"function\") {\r\n throw new TypeError(expected + \" is not a function\");\r\n }\r\n};\r\nvar noop = function () {\r\n};\r\nvar catchRejection = function (promise2, onError) {\r\n if (onError === void 0) { onError = noop; }\r\n promise2.catch(onError);\r\n return promise2;\r\n};\r\nvar addAbortSignalListener = function (abortSignal, callback) {\r\n abortSignal.addEventListener(\"abort\", callback, { once: true });\r\n return function () { return abortSignal.removeEventListener(\"abort\", callback); };\r\n};\r\nvar abortControllerWithReason = function (abortController, reason) {\r\n var signal = abortController.signal;\r\n if (signal.aborted) {\r\n return;\r\n }\r\n if (!(\"reason\" in signal)) {\r\n Object.defineProperty(signal, \"reason\", {\r\n enumerable: true,\r\n value: reason,\r\n configurable: true,\r\n writable: true\r\n });\r\n }\r\n ;\r\n abortController.abort(reason);\r\n};\r\n// src/listenerMiddleware/exceptions.ts\r\nvar task = \"task\";\r\nvar listener = \"listener\";\r\nvar completed = \"completed\";\r\nvar cancelled = \"cancelled\";\r\nvar taskCancelled = \"task-\" + cancelled;\r\nvar taskCompleted = \"task-\" + completed;\r\nvar listenerCancelled = listener + \"-\" + cancelled;\r\nvar listenerCompleted = listener + \"-\" + completed;\r\nvar TaskAbortError = /** @class */ (function () {\r\n function TaskAbortError(code) {\r\n this.code = code;\r\n this.name = \"TaskAbortError\";\r\n this.message = task + \" \" + cancelled + \" (reason: \" + code + \")\";\r\n }\r\n return TaskAbortError;\r\n}());\r\n// src/listenerMiddleware/task.ts\r\nvar validateActive = function (signal) {\r\n if (signal.aborted) {\r\n throw new TaskAbortError(signal.reason);\r\n }\r\n};\r\nfunction raceWithSignal(signal, promise2) {\r\n var cleanup = noop;\r\n return new Promise(function (resolve, reject) {\r\n var notifyRejection = function () { return reject(new TaskAbortError(signal.reason)); };\r\n if (signal.aborted) {\r\n notifyRejection();\r\n return;\r\n }\r\n cleanup = addAbortSignalListener(signal, notifyRejection);\r\n promise2.finally(function () { return cleanup(); }).then(resolve, reject);\r\n }).finally(function () {\r\n cleanup = noop;\r\n });\r\n}\r\nvar runTask = function (task2, cleanUp) { return __async(void 0, null, function () {\r\n var value, error_1;\r\n return __generator(this, function (_c) {\r\n switch (_c.label) {\r\n case 0:\r\n _c.trys.push([0, 3, 4, 5]);\r\n return [4 /*yield*/, Promise.resolve()];\r\n case 1:\r\n _c.sent();\r\n return [4 /*yield*/, task2()];\r\n case 2:\r\n value = _c.sent();\r\n return [2 /*return*/, {\r\n status: \"ok\",\r\n value: value\r\n }];\r\n case 3:\r\n error_1 = _c.sent();\r\n return [2 /*return*/, {\r\n status: error_1 instanceof TaskAbortError ? \"cancelled\" : \"rejected\",\r\n error: error_1\r\n }];\r\n case 4:\r\n cleanUp == null ? void 0 : cleanUp();\r\n return [7 /*endfinally*/];\r\n case 5: return [2 /*return*/];\r\n }\r\n });\r\n}); };\r\nvar createPause = function (signal) {\r\n return function (promise2) {\r\n return catchRejection(raceWithSignal(signal, promise2).then(function (output) {\r\n validateActive(signal);\r\n return output;\r\n }));\r\n };\r\n};\r\nvar createDelay = function (signal) {\r\n var pause = createPause(signal);\r\n return function (timeoutMs) {\r\n return pause(new Promise(function (resolve) { return setTimeout(resolve, timeoutMs); }));\r\n };\r\n};\r\n// src/listenerMiddleware/index.ts\r\nvar assign = Object.assign;\r\nvar INTERNAL_NIL_TOKEN = {};\r\nvar alm = \"listenerMiddleware\";\r\nvar createFork = function (parentAbortSignal, parentBlockingPromises) {\r\n var linkControllers = function (controller) { return addAbortSignalListener(parentAbortSignal, function () { return abortControllerWithReason(controller, parentAbortSignal.reason); }); };\r\n return function (taskExecutor, opts) {\r\n assertFunction(taskExecutor, \"taskExecutor\");\r\n var childAbortController = new AbortController();\r\n linkControllers(childAbortController);\r\n var result = runTask(function () { return __async(void 0, null, function () {\r\n var result2;\r\n return __generator(this, function (_c) {\r\n switch (_c.label) {\r\n case 0:\r\n validateActive(parentAbortSignal);\r\n validateActive(childAbortController.signal);\r\n return [4 /*yield*/, taskExecutor({\r\n pause: createPause(childAbortController.signal),\r\n delay: createDelay(childAbortController.signal),\r\n signal: childAbortController.signal\r\n })];\r\n case 1:\r\n result2 = _c.sent();\r\n validateActive(childAbortController.signal);\r\n return [2 /*return*/, result2];\r\n }\r\n });\r\n }); }, function () { return abortControllerWithReason(childAbortController, taskCompleted); });\r\n if (opts == null ? void 0 : opts.autoJoin) {\r\n parentBlockingPromises.push(result);\r\n }\r\n return {\r\n result: createPause(parentAbortSignal)(result),\r\n cancel: function () {\r\n abortControllerWithReason(childAbortController, taskCancelled);\r\n }\r\n };\r\n };\r\n};\r\nvar createTakePattern = function (startListening, signal) {\r\n var take = function (predicate, timeout) { return __async(void 0, null, function () {\r\n var unsubscribe, tuplePromise, promises, output;\r\n return __generator(this, function (_c) {\r\n switch (_c.label) {\r\n case 0:\r\n validateActive(signal);\r\n unsubscribe = function () {\r\n };\r\n tuplePromise = new Promise(function (resolve, reject) {\r\n var stopListening = startListening({\r\n predicate: predicate,\r\n effect: function (action, listenerApi) {\r\n listenerApi.unsubscribe();\r\n resolve([\r\n action,\r\n listenerApi.getState(),\r\n listenerApi.getOriginalState()\r\n ]);\r\n }\r\n });\r\n unsubscribe = function () {\r\n stopListening();\r\n reject();\r\n };\r\n });\r\n promises = [\r\n tuplePromise\r\n ];\r\n if (timeout != null) {\r\n promises.push(new Promise(function (resolve) { return setTimeout(resolve, timeout, null); }));\r\n }\r\n _c.label = 1;\r\n case 1:\r\n _c.trys.push([1, , 3, 4]);\r\n return [4 /*yield*/, raceWithSignal(signal, Promise.race(promises))];\r\n case 2:\r\n output = _c.sent();\r\n validateActive(signal);\r\n return [2 /*return*/, output];\r\n case 3:\r\n unsubscribe();\r\n return [7 /*endfinally*/];\r\n case 4: return [2 /*return*/];\r\n }\r\n });\r\n }); };\r\n return function (predicate, timeout) { return catchRejection(take(predicate, timeout)); };\r\n};\r\nvar getListenerEntryPropsFrom = function (options) {\r\n var type = options.type, actionCreator = options.actionCreator, matcher = options.matcher, predicate = options.predicate, effect = options.effect;\r\n if (type) {\r\n predicate = createAction(type).match;\r\n }\r\n else if (actionCreator) {\r\n type = actionCreator.type;\r\n predicate = actionCreator.match;\r\n }\r\n else if (matcher) {\r\n predicate = matcher;\r\n }\r\n else if (predicate) {\r\n }\r\n else {\r\n throw new Error(\"Creating or removing a listener requires one of the known fields for matching an action\");\r\n }\r\n assertFunction(effect, \"options.listener\");\r\n return { predicate: predicate, type: type, effect: effect };\r\n};\r\nvar createListenerEntry = function (options) {\r\n var _c = getListenerEntryPropsFrom(options), type = _c.type, predicate = _c.predicate, effect = _c.effect;\r\n var id = nanoid();\r\n var entry = {\r\n id: id,\r\n effect: effect,\r\n type: type,\r\n predicate: predicate,\r\n pending: new Set(),\r\n unsubscribe: function () {\r\n throw new Error(\"Unsubscribe not initialized\");\r\n }\r\n };\r\n return entry;\r\n};\r\nvar cancelActiveListeners = function (entry) {\r\n entry.pending.forEach(function (controller) {\r\n abortControllerWithReason(controller, listenerCancelled);\r\n });\r\n};\r\nvar createClearListenerMiddleware = function (listenerMap) {\r\n return function () {\r\n listenerMap.forEach(cancelActiveListeners);\r\n listenerMap.clear();\r\n };\r\n};\r\nvar safelyNotifyError = function (errorHandler, errorToNotify, errorInfo) {\r\n try {\r\n errorHandler(errorToNotify, errorInfo);\r\n }\r\n catch (errorHandlerError) {\r\n setTimeout(function () {\r\n throw errorHandlerError;\r\n }, 0);\r\n }\r\n};\r\nvar addListener = createAction(alm + \"/add\");\r\nvar clearAllListeners = createAction(alm + \"/removeAll\");\r\nvar removeListener = createAction(alm + \"/remove\");\r\nvar defaultErrorHandler = function () {\r\n var args = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n args[_i] = arguments[_i];\r\n }\r\n console.error.apply(console, __spreadArray([alm + \"/error\"], args));\r\n};\r\nfunction createListenerMiddleware(middlewareOptions) {\r\n var _this = this;\r\n if (middlewareOptions === void 0) { middlewareOptions = {}; }\r\n var listenerMap = new Map();\r\n var extra = middlewareOptions.extra, _c = middlewareOptions.onError, onError = _c === void 0 ? defaultErrorHandler : _c;\r\n assertFunction(onError, \"onError\");\r\n var insertEntry = function (entry) {\r\n entry.unsubscribe = function () { return listenerMap.delete(entry.id); };\r\n listenerMap.set(entry.id, entry);\r\n return function (cancelOptions) {\r\n entry.unsubscribe();\r\n if (cancelOptions == null ? void 0 : cancelOptions.cancelActive) {\r\n cancelActiveListeners(entry);\r\n }\r\n };\r\n };\r\n var findListenerEntry = function (comparator) {\r\n for (var _i = 0, _c = Array.from(listenerMap.values()); _i < _c.length; _i++) {\r\n var entry = _c[_i];\r\n if (comparator(entry)) {\r\n return entry;\r\n }\r\n }\r\n return void 0;\r\n };\r\n var startListening = function (options) {\r\n var entry = findListenerEntry(function (existingEntry) { return existingEntry.effect === options.effect; });\r\n if (!entry) {\r\n entry = createListenerEntry(options);\r\n }\r\n return insertEntry(entry);\r\n };\r\n var stopListening = function (options) {\r\n var _c = getListenerEntryPropsFrom(options), type = _c.type, effect = _c.effect, predicate = _c.predicate;\r\n var entry = findListenerEntry(function (entry2) {\r\n var matchPredicateOrType = typeof type === \"string\" ? entry2.type === type : entry2.predicate === predicate;\r\n return matchPredicateOrType && entry2.effect === effect;\r\n });\r\n if (entry) {\r\n entry.unsubscribe();\r\n if (options.cancelActive) {\r\n cancelActiveListeners(entry);\r\n }\r\n }\r\n return !!entry;\r\n };\r\n var notifyListener = function (entry, action, api, getOriginalState) { return __async(_this, null, function () {\r\n var internalTaskController, take, autoJoinPromises, listenerError_1;\r\n return __generator(this, function (_c) {\r\n switch (_c.label) {\r\n case 0:\r\n internalTaskController = new AbortController();\r\n take = createTakePattern(startListening, internalTaskController.signal);\r\n autoJoinPromises = [];\r\n _c.label = 1;\r\n case 1:\r\n _c.trys.push([1, 3, 4, 6]);\r\n entry.pending.add(internalTaskController);\r\n return [4 /*yield*/, Promise.resolve(entry.effect(action, assign({}, api, {\r\n getOriginalState: getOriginalState,\r\n condition: function (predicate, timeout) { return take(predicate, timeout).then(Boolean); },\r\n take: take,\r\n delay: createDelay(internalTaskController.signal),\r\n pause: createPause(internalTaskController.signal),\r\n extra: extra,\r\n signal: internalTaskController.signal,\r\n fork: createFork(internalTaskController.signal, autoJoinPromises),\r\n unsubscribe: entry.unsubscribe,\r\n subscribe: function () {\r\n listenerMap.set(entry.id, entry);\r\n },\r\n cancelActiveListeners: function () {\r\n entry.pending.forEach(function (controller, _, set) {\r\n if (controller !== internalTaskController) {\r\n abortControllerWithReason(controller, listenerCancelled);\r\n set.delete(controller);\r\n }\r\n });\r\n }\r\n })))];\r\n case 2:\r\n _c.sent();\r\n return [3 /*break*/, 6];\r\n case 3:\r\n listenerError_1 = _c.sent();\r\n if (!(listenerError_1 instanceof TaskAbortError)) {\r\n safelyNotifyError(onError, listenerError_1, {\r\n raisedBy: \"effect\"\r\n });\r\n }\r\n return [3 /*break*/, 6];\r\n case 4: return [4 /*yield*/, Promise.allSettled(autoJoinPromises)];\r\n case 5:\r\n _c.sent();\r\n abortControllerWithReason(internalTaskController, listenerCompleted);\r\n entry.pending.delete(internalTaskController);\r\n return [7 /*endfinally*/];\r\n case 6: return [2 /*return*/];\r\n }\r\n });\r\n }); };\r\n var clearListenerMiddleware = createClearListenerMiddleware(listenerMap);\r\n var middleware = function (api) { return function (next) { return function (action) {\r\n if (!isAction(action)) {\r\n return next(action);\r\n }\r\n if (addListener.match(action)) {\r\n return startListening(action.payload);\r\n }\r\n if (clearAllListeners.match(action)) {\r\n clearListenerMiddleware();\r\n return;\r\n }\r\n if (removeListener.match(action)) {\r\n return stopListening(action.payload);\r\n }\r\n var originalState = api.getState();\r\n var getOriginalState = function () {\r\n if (originalState === INTERNAL_NIL_TOKEN) {\r\n throw new Error(alm + \": getOriginalState can only be called synchronously\");\r\n }\r\n return originalState;\r\n };\r\n var result;\r\n try {\r\n result = next(action);\r\n if (listenerMap.size > 0) {\r\n var currentState = api.getState();\r\n var listenerEntries = Array.from(listenerMap.values());\r\n for (var _i = 0, listenerEntries_1 = listenerEntries; _i < listenerEntries_1.length; _i++) {\r\n var entry = listenerEntries_1[_i];\r\n var runListener = false;\r\n try {\r\n runListener = entry.predicate(action, currentState, originalState);\r\n }\r\n catch (predicateError) {\r\n runListener = false;\r\n safelyNotifyError(onError, predicateError, {\r\n raisedBy: \"predicate\"\r\n });\r\n }\r\n if (!runListener) {\r\n continue;\r\n }\r\n notifyListener(entry, action, api, getOriginalState);\r\n }\r\n }\r\n }\r\n finally {\r\n originalState = INTERNAL_NIL_TOKEN;\r\n }\r\n return result;\r\n }; }; };\r\n return {\r\n middleware: middleware,\r\n startListening: startListening,\r\n stopListening: stopListening,\r\n clearListeners: clearListenerMiddleware\r\n };\r\n}\r\n// src/autoBatchEnhancer.ts\r\nvar SHOULD_AUTOBATCH = \"RTK_autoBatch\";\r\nvar prepareAutoBatched = function () { return function (payload) {\r\n var _c;\r\n return ({\r\n payload: payload,\r\n meta: (_c = {}, _c[SHOULD_AUTOBATCH] = true, _c)\r\n });\r\n}; };\r\nvar promise;\r\nvar queueMicrotaskShim = typeof queueMicrotask === \"function\" ? queueMicrotask.bind(typeof window !== \"undefined\" ? window : typeof global !== \"undefined\" ? global : globalThis) : function (cb) { return (promise || (promise = Promise.resolve())).then(cb).catch(function (err) { return setTimeout(function () {\r\n throw err;\r\n}, 0); }); };\r\nvar createQueueWithTimer = function (timeout) {\r\n return function (notify) {\r\n setTimeout(notify, timeout);\r\n };\r\n};\r\nvar rAF = typeof window !== \"undefined\" && window.requestAnimationFrame ? window.requestAnimationFrame : createQueueWithTimer(10);\r\nvar autoBatchEnhancer = function (options) {\r\n if (options === void 0) { options = { type: \"raf\" }; }\r\n return function (next) { return function () {\r\n var args = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n args[_i] = arguments[_i];\r\n }\r\n var store = next.apply(void 0, args);\r\n var notifying = true;\r\n var shouldNotifyAtEndOfTick = false;\r\n var notificationQueued = false;\r\n var listeners = new Set();\r\n var queueCallback = options.type === \"tick\" ? queueMicrotaskShim : options.type === \"raf\" ? rAF : options.type === \"callback\" ? options.queueNotification : createQueueWithTimer(options.timeout);\r\n var notifyListeners = function () {\r\n notificationQueued = false;\r\n if (shouldNotifyAtEndOfTick) {\r\n shouldNotifyAtEndOfTick = false;\r\n listeners.forEach(function (l) { return l(); });\r\n }\r\n };\r\n return Object.assign({}, store, {\r\n subscribe: function (listener2) {\r\n var wrappedListener = function () { return notifying && listener2(); };\r\n var unsubscribe = store.subscribe(wrappedListener);\r\n listeners.add(listener2);\r\n return function () {\r\n unsubscribe();\r\n listeners.delete(listener2);\r\n };\r\n },\r\n dispatch: function (action) {\r\n var _a;\r\n try {\r\n notifying = !((_a = action == null ? void 0 : action.meta) == null ? void 0 : _a[SHOULD_AUTOBATCH]);\r\n shouldNotifyAtEndOfTick = !notifying;\r\n if (shouldNotifyAtEndOfTick) {\r\n if (!notificationQueued) {\r\n notificationQueued = true;\r\n queueCallback(notifyListeners);\r\n }\r\n }\r\n return store.dispatch(action);\r\n }\r\n finally {\r\n notifying = true;\r\n }\r\n }\r\n });\r\n }; };\r\n};\r\n// src/index.ts\r\nenableES5();\r\nexport { EnhancerArray, MiddlewareArray, SHOULD_AUTOBATCH, TaskAbortError, addListener, autoBatchEnhancer, clearAllListeners, configureStore, createAction, createActionCreatorInvariantMiddleware, createAsyncThunk, createDraftSafeSelector, createEntityAdapter, createImmutableStateInvariantMiddleware, createListenerMiddleware, default2 as createNextState, createReducer, createSelector2 as createSelector, createSerializableStateInvariantMiddleware, createSlice, current2 as current, findNonSerializableValue, freeze, getDefaultMiddleware, getType, isAction, isActionCreator, isAllOf, isAnyOf, isAsyncThunkAction, isDraft4 as isDraft, isFSA as isFluxStandardAction, isFulfilled, isImmutableDefault, isPending, isPlain, isPlainObject, isRejected, isRejectedWithValue, miniSerializeError, nanoid, original, prepareAutoBatched, removeListener, unwrapResult };\r\n//# sourceMappingURL=redux-toolkit.esm.js.map", "import {createAction} from \"@reduxjs/toolkit\";\nimport type {WebcastAuctionConnectData_TypeDef} from \"../services/AuctionsManager\";\nimport type {Bid, ChatMessage, Lot, LotDetails, PMAuctionDataSnapshot, PMBiddingUpdated, PMChoiceLotsSelected, PMParticipantsUpdated, PMWebcastStatusChanged, Round} from \"../data/data_types_definitions\";\n\n\nexport const ACTION_TYPES = {\n\n\n WEBCAST_WBS_COMM_STATE_UPDATE: 'WEBCAST/WBS_COMM_STATE_UPDATE',\n WEBCAST_WBS_NETWORK_STATUS_UPDATE: 'WEBCAST/WBS_NETWORK_STATUS_UPDATE',\n\n\n WEBCAST_AUCTION_INIT: 'WEBCAST/SALE_INIT',\n WEBCAST_AUCTION_CLEAR: 'WEBCAST/SALE_CLEAR',\n\n\n WEBCAST_AUCTION_DATA_SNAPSHOT_INIT: 'WEBCAST/AUCTION_DATA_SNAPSHOT_INIT',\n\n\n WEBCAST_AUCTION_DATA_SYNC_LOTS_LIST_UPDATE: 'WEBCAST/AUCTION_DATA_SYNC_LOTS_LIST_UPDATE',\n\n WEBCAST_AUCTION_DATA_LOTS_DETAILS_UPDATE: 'WEBCAST/AUCTION_DATA_LOTS_DETAILS_UPDATE', // lots details via Rails client API\n\n WEBCAST_STATUS_CHANGE: 'WEBCAST/STATUS_CHANGE',\n\n WEBCAST_CURRENT_ROUND_CREATE: 'WEBCAST/CURRENT_ROUND_CREATE',\n WEBCAST_CURRENT_ROUND_BIDDING_UPDATE: 'WEBCAST/CURRENT_ROUND_BIDDING_UPDATE',\n WEBCAST_CURRENT_ROUND_STOP: 'WEBCAST/CURRENT_ROUND_STOP',\n WEBCAST_CURRENT_ROUND_CLOSE: 'WEBCAST/CURRENT_ROUND_CLOSE',\n WEBCAST_CHOICE_LOTS_SELECTION_UPDATE: 'WEBCAST/CHOICE_LOTS_SELECTION_UPDATE',\n\n WEBCAST_LOTS_PASS_CLOSE: 'WEBCAST/LOTS_PASS_CLOSE',\n\n\n WEBCAST_CHAT_MESSAGE_POST: 'WEBCAST/CHAT_MESSAGE_POST', //\n WEBCAST_CHAT_ROOM_OPEN_AND_READ: 'WEBCAST/CHAT_ROOM_OPEN_AND_READ', //\n WEBCAST_CHAT_ROOM_CLOSE: 'WEBCAST/CHAT_ROOM_CLOSE', //\n\n\n\n //-- begin Clerk specific\n WEBCAST_CLERK_PARTICIPANTS_UPDATE: 'WEBCAST/CLERK_PARTICIPANTS_UPDATE',\n WEBCAST_CLERK_AUCTION_DATA_SYNC_CHECK_STATUS_UPDATE: 'WEBCAST_CLERK_AUCTION_DATA_SYNC_CHECK_STATUS_UPDATE',\n\n //-- end Clerk specific\n};\n\n\n\nexport class ActionBuilder {\n static build(actionType, payload = null, meta = null) {\n return {\n type: actionType,\n payload: payload,\n meta: meta,\n error: (payload instanceof Error)\n };\n }\n}\n\n\n\n\nexport type CurrentRoundStopActionPayloadType = {\n roundId:string,\n roundType:number,\n stopType:number,\n highestBid:Bid,\n nextRound:Round,\n\n choiceLotsIds:Array,\n choiceUsersIds:Array,\n\n isTransitional?:boolean,\n}\n\n\nexport type CurrentRoundCloseActionPayloadType = {\n roundId:string,\n roundType:number,\n stopType:number,\n lotsIds:Array,\n bidsHistory:Array,\n highestBid:Bid,\n\n nextRound:Round,\n\n choiceLotsIds?:Array,\n choiceUsersIds?:Array,\n}\n\n\nexport type WbsNetworkStatusUpdatePayloadType = {\n connectionState: WbsNetworkStatusConnectionStateEnum,\n roundTripMilliseconds:number|false,\n}\n\n\nexport enum ChannelEnum {\n all = '*',\n bidding = 'bidding',\n chat = 'chat',\n}\n\n\nexport type WbsCommStateUpdatePayloadType = {\n channel: ChannelEnum,\n newStatus: WbsCommStatesEnum,\n}\n\nexport enum WbsCommStatesEnum {\n WBS_COMM_STATUS_UNINITIALIZED= 'uninitialized',\n WBS_COMM_STATUS_INITIALIZED = 'initialized',\n WBS_COMM_STATUS_IDLE = 'idle',\n WBS_COMM_STATUS_SENDING = 'sending',\n WBS_COMM_STATUS_ERROR = 'error',\n}\n\nexport enum WbsNetworkStatusConnectionStateEnum {\n connecting = 1,\n connected = 9,\n disconnected = -1,\n}\n\n\n\nexport const ActionsCreators = {\n\n webcast: {\n\n wbsCommStateUpdate: createAction(ACTION_TYPES.WEBCAST_WBS_COMM_STATE_UPDATE),\n\n wbsNetworkStatusUpdate: createAction(ACTION_TYPES.WEBCAST_WBS_NETWORK_STATUS_UPDATE),\n\n\n webcastAuctionInit: createAction(ACTION_TYPES.WEBCAST_AUCTION_INIT),\n\n\n webcastAuctionClear: createAction(ACTION_TYPES.WEBCAST_AUCTION_CLEAR),\n\n\n webcastAuctionDataSnapshotInit: createAction(ACTION_TYPES.WEBCAST_AUCTION_DATA_SNAPSHOT_INIT),\n\n webcastClerkAuctionDataSyncCheckStatusUpdate: createAction(ACTION_TYPES.WEBCAST_CLERK_AUCTION_DATA_SYNC_CHECK_STATUS_UPDATE),\n\n webcastAuctionDataSyncLotsListUpdate: createAction>(ACTION_TYPES.WEBCAST_AUCTION_DATA_SYNC_LOTS_LIST_UPDATE),\n\n webcastAuctionDataLotsDetailsUpdate: createAction<{lotsDetails:Array,isDataSync?:boolean}>(ACTION_TYPES.WEBCAST_AUCTION_DATA_LOTS_DETAILS_UPDATE),\n\n webcastStatusChange: createAction(ACTION_TYPES.WEBCAST_STATUS_CHANGE),\n\n webcastClerkParticipantsUpdate: createAction(ACTION_TYPES.WEBCAST_CLERK_PARTICIPANTS_UPDATE),\n\n webcastCurrentRoundBiddingUpdate: createAction(ACTION_TYPES.WEBCAST_CURRENT_ROUND_BIDDING_UPDATE),\n\n webcastCurrentRoundStop: createAction(ACTION_TYPES.WEBCAST_CURRENT_ROUND_STOP),\n\n webcastCurrentRoundClose: createAction(ACTION_TYPES.WEBCAST_CURRENT_ROUND_CLOSE),\n\n webcastLotsPassClose: createAction(ACTION_TYPES.WEBCAST_LOTS_PASS_CLOSE),\n\n choiceLotsSelectionUpdate: function webcastChoiceLotsSelectionUpdate(msgPayload:PMChoiceLotsSelected) {\n return ActionBuilder.build(ACTION_TYPES.WEBCAST_CHOICE_LOTS_SELECTION_UPDATE, msgPayload);\n },\n\n\n webcastChatMessagePost: createAction(ACTION_TYPES.WEBCAST_CHAT_MESSAGE_POST),\n\n webcastChatRoomOpenAndMarkAsRead: createAction(ACTION_TYPES.WEBCAST_CHAT_ROOM_OPEN_AND_READ),\n\n webcastChatRoomClose: createAction(ACTION_TYPES.WEBCAST_CHAT_ROOM_CLOSE)\n },\n}\n", "import React from \"react\";\nimport {connect} from \"react-redux\";\nimport {ReduxWebcastWbsNetworkStatusType} from \"@nextlot/core/webcast/redux/webcast/reducerWbsNetworkStatus\";\nimport {ReduxStateType} from \"@nextlot/core/webcast/services/DataStore\";\nimport {ChannelEnum} from \"@nextlot/core/webcast/redux/actions\";\n\n\ntype CmpPropsType = {\n wbsCommChannel:string,\n wbsNetworkStatus:ReduxWebcastWbsNetworkStatusType,\n}\n\n\nconst NetworkAwareBusyOverlayCmp = (props:CmpPropsType) => {\n let channelBusy = false;\n if (props.wbsCommChannel === ChannelEnum.bidding) {\n channelBusy = props.wbsNetworkStatus.biddingCommBusy;\n }\n else if (props.wbsCommChannel === ChannelEnum.chat) {\n channelBusy = props.wbsNetworkStatus.chatCommBusy;\n }\n else {\n channelBusy = props.wbsNetworkStatus.biddingCommBusy || props.wbsNetworkStatus.chatCommBusy; // either channel is busy\n }\n\n return channelBusy ?

: null;\n};\n\nNetworkAwareBusyOverlayCmp.defaultProps = {\n wbsCommChannel: ChannelEnum.bidding,\n};\n\n\n\nexport default connect(({ activeWebcast }:ReduxStateType) => {\n return {\n wbsNetworkStatus: activeWebcast.wbsNetworkStatus\n };\n})(NetworkAwareBusyOverlayCmp);\n\n", "\nexport default class TaggedLogger {\n\n static get(tagPrefix:string) {\n return new TaggedLogger(tagPrefix);\n };\n\n\n\n tagPrefix: string;\n\n\n constructor(logProducer:any) {\n\n let producerTag:string;\n\n if (typeof logProducer === 'function') {\n producerTag = logProducer.name;\n }\n else if (typeof logProducer === 'object') {\n throw new Error('TaggerLogger ERROR: invalid logProducer of type object');\n }\n else {\n producerTag = String(logProducer);\n }\n\n this.tagPrefix = `[${producerTag}]`;\n }\n\n\n $updateTagPrefix(newTagPrefix:string):void {\n this.tagPrefix = `[${newTagPrefix}]`;\n }\n\n\n debug(...args:Array) {\n console.debug(this.tagPrefix, ...args);\n }\n\n log(...args:Array) {\n console.log(this.tagPrefix, ...args);\n }\n\n info(...args:Array) {\n console.info(this.tagPrefix, ...args);\n }\n\n warn(...args:Array) {\n console.warn(this.tagPrefix, ...args);\n }\n\n error(...args:Array) {\n console.error(this.tagPrefix, ...args);\n }\n}\n", "import TaggedLogger from \"./TaggedLogger\";\n\nconst _loggerEB = TaggedLogger.get('EventBus');\n\ntype ListenerFunction = (data?:any)=>void\n\nexport class EventBus {\n private readonly allListenersMap: Map>;\n\n constructor() {\n this.allListenersMap = new Map(); // >\n }\n\n on = (eventType:string, listenerFn:ListenerFunction):()=>void => {\n let eventTypeListeners:Set = this.allListenersMap.get(eventType);\n if (!eventTypeListeners) {\n eventTypeListeners = new Set();\n this.allListenersMap.set(eventType, eventTypeListeners);\n }\n eventTypeListeners.add(listenerFn);\n return () => {\n eventTypeListeners.delete(listenerFn);\n }\n }\n\n emit = (eventType:string, data?:any) => {\n const typeListeners:Set = this.allListenersMap.get(eventType);\n if (!typeListeners) {\n return;\n }\n\n typeListeners.forEach((listenerFn) => {\n listenerFn(data);\n });\n }\n\n offAll = (eventType:string) => {\n this.allListenersMap.delete(eventType);\n }\n}\n\n\nconst _loggerSTEB = TaggedLogger.get('SingleTypeEventBus');\n\nexport class SingleTypeEventBus {\n\n private _eb: EventBus;\n\n constructor() {\n this._eb = new EventBus();\n }\n\n on = (handlerFn:(data?:T)=>void) => {\n return this._eb.on('_default', handlerFn);\n }\n\n emit = (data?:T) => {\n this._eb.emit('_default', data);\n }\n\n offAll = () => {\n this._eb.offAll('_default');\n }\n}\n\n\nexport class SimpleStoredDataEventBus {\n private data: T;\n private handlerFn: (data:T)=>void|null\n\n constructor(init:T = null) {\n this.data = init;\n this.handlerFn = null;\n }\n\n registerHandler = (handlerFn: (data:T)=>void) => {\n this.handlerFn = handlerFn;\n if (this.data) {\n this.handlerFn(this.data);\n this.data = null;\n }\n }\n\n\n unregisterHandler = () => {\n this.handlerFn = null;\n }\n\n emit = (data:T) => {\n this.data = data;\n if (this.handlerFn) {\n this.handlerFn(data);\n this.data = null;\n }\n }\n\n\n}\n", "import {EventBus} from \"./EventBus\";\nimport TaggedLogger from \"./TaggedLogger\";\n\nconst _logger = TaggedLogger.get('TimerEventsEmitter');\n\ntype ListenerFunction = (param?: T)=>void;\ntype UnsubscribeFunction = ()=>void;\n\nlet _defaultInstance:TimerEventsEmitter;\n\nconst EVENT_TYPES = {\n tickSecond: 'tick.second',\n tickMinute: 'tick.minute',\n serverUnixTimestampUpdate: 'serverUnixTimestamp.update',\n}\n\nexport default class TimerEventsEmitter {\n private readonly _eventBus:EventBus;\n private _intervalId;\n private _syncedServerUnixTimestamp: number;\n\n\n static init() {\n if (_defaultInstance) {\n throw 'already initialized';\n }\n _defaultInstance = new TimerEventsEmitter();\n _logger.info('.init: initialized! ');\n\n ((window || global || {}) as any)._dev_TimerEventsEmitter_instance = _defaultInstance;\n return _defaultInstance;\n }\n\n\n\n constructor(serverUnixTimestamp = 0) {\n this._eventBus = new EventBus();\n this._syncedServerUnixTimestamp = serverUnixTimestamp;\n this._intervalId = setInterval(() => {\n this._syncedServerUnixTimestamp += 1;\n\n // _logger.debug('.tick ~', this._syncedServerUnixTimestamp);\n\n this._eventBus.emit(EVENT_TYPES.tickSecond);\n if (this._syncedServerUnixTimestamp % 60 === 0) {\n this._eventBus.emit(EVENT_TYPES.tickMinute);\n }\n }, 1_000);\n }\n\n updateServerUnixTimestamp(serverUnixTimestamp:number) {\n // const previousValue = this._syncedServerUnixTimestamp;\n // _logger.debug('.updateServerUnixTimestamp: [', previousValue, '] -> [', serverUnixTimestamp, ']: diff: ', serverUnixTimestamp - previousValue);\n this._syncedServerUnixTimestamp = serverUnixTimestamp;\n this._eventBus.emit(EVENT_TYPES.serverUnixTimestampUpdate, serverUnixTimestamp);\n }\n\n\n onEverySecond(cbFn:ListenerFunction):UnsubscribeFunction {\n return this._eventBus.on(EVENT_TYPES.tickSecond, cbFn);\n }\n\n\n onEveryMinute(cbFn:ListenerFunction):UnsubscribeFunction {\n return this._eventBus.on(EVENT_TYPES.tickMinute,cbFn);\n }\n\n onServerUnixTimestampUpdate(cbFn:ListenerFunction):UnsubscribeFunction {\n return this._eventBus.on(EVENT_TYPES.serverUnixTimestampUpdate, cbFn);\n }\n\n\n onEvery(durationSeconds:number, cbFn:ListenerFunction):UnsubscribeFunction {\n const intervalId = setInterval(cbFn, durationSeconds);\n return () => {\n clearInterval(intervalId);\n }\n }\n\n}\n", "export { default as TaggedLogger } from \"./TaggedLogger\";\n\nexport { EventBus, SingleTypeEventBus, SimpleStoredDataEventBus } from \"./EventBus\";\n\nexport { default as TimerEventsEmitter } from \"./TimerEventsEmitter\";\n\nexport function pluralize(count:number, pluralForm:string, singularForm:string = null):string {\n if (count === 1) {\n return `1 ${singularForm || pluralForm}`;\n }\n return `${count} ${pluralForm}`;\n}\n\n\nexport function numberAsString(n:number, stringValueWhenNaN:string = ''):string {\n return isNaN(n) ? stringValueWhenNaN : String(n);\n}\n\n\nexport const loadExternalJsScript = (url: string, onLoadFn:(args?: any) => any, onLoadArgs?:any) => {\n\n const scriptEl = document.createElement('script');\n scriptEl.type = 'text/javascript';\n scriptEl.src = url;\n scriptEl.async = true;\n\n scriptEl.onerror = (err) => {\n console.error('NextLot Nexus]js:script#onerror: ', url, err);\n }\n\n scriptEl.onload = function() {\n onLoadFn(onLoadArgs);\n }\n\n document.head.appendChild(scriptEl);\n}\n\n\nexport function runOnDOMContentLoaded(callbackFn:(args?:any)=>any, cbArgs?:any) {\n if (document.readyState === 'loading') {\n // loading hasn't finished yet\n document.addEventListener('DOMContentLoaded', function() { callbackFn(cbArgs) });\n }\n else {\n // content already loaded (readyState === 'interactive' or 'complete')\n callbackFn(cbArgs);\n }\n}\n\n\n\nexport const isDevelopmentEnv = false;\n", "/*! https://mths.be/punycode v1.4.0 by @mathias */\n;(function(root) {\n\n\t/** Detect free variables */\n\tvar freeExports = typeof exports == 'object' && exports &&\n\t\t!exports.nodeType && exports;\n\tvar freeModule = typeof module == 'object' && module &&\n\t\t!module.nodeType && module;\n\tvar freeGlobal = typeof global == 'object' && global;\n\tif (\n\t\tfreeGlobal.global === freeGlobal ||\n\t\tfreeGlobal.window === freeGlobal ||\n\t\tfreeGlobal.self === freeGlobal\n\t) {\n\t\troot = freeGlobal;\n\t}\n\n\t/**\n\t * The `punycode` object.\n\t * @name punycode\n\t * @type Object\n\t */\n\tvar punycode,\n\n\t/** Highest positive signed 32-bit float value */\n\tmaxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1\n\n\t/** Bootstring parameters */\n\tbase = 36,\n\ttMin = 1,\n\ttMax = 26,\n\tskew = 38,\n\tdamp = 700,\n\tinitialBias = 72,\n\tinitialN = 128, // 0x80\n\tdelimiter = '-', // '\\x2D'\n\n\t/** Regular expressions */\n\tregexPunycode = /^xn--/,\n\tregexNonASCII = /[^\\x20-\\x7E]/, // unprintable ASCII chars + non-ASCII chars\n\tregexSeparators = /[\\x2E\\u3002\\uFF0E\\uFF61]/g, // RFC 3490 separators\n\n\t/** Error messages */\n\terrors = {\n\t\t'overflow': 'Overflow: input needs wider integers to process',\n\t\t'not-basic': 'Illegal input >= 0x80 (not a basic code point)',\n\t\t'invalid-input': 'Invalid input'\n\t},\n\n\t/** Convenience shortcuts */\n\tbaseMinusTMin = base - tMin,\n\tfloor = Math.floor,\n\tstringFromCharCode = String.fromCharCode,\n\n\t/** Temporary variable */\n\tkey;\n\n\t/*--------------------------------------------------------------------------*/\n\n\t/**\n\t * A generic error utility function.\n\t * @private\n\t * @param {String} type The error type.\n\t * @returns {Error} Throws a `RangeError` with the applicable error message.\n\t */\n\tfunction error(type) {\n\t\tthrow new RangeError(errors[type]);\n\t}\n\n\t/**\n\t * A generic `Array#map` utility function.\n\t * @private\n\t * @param {Array} array The array to iterate over.\n\t * @param {Function} callback The function that gets called for every array\n\t * item.\n\t * @returns {Array} A new array of values returned by the callback function.\n\t */\n\tfunction map(array, fn) {\n\t\tvar length = array.length;\n\t\tvar result = [];\n\t\twhile (length--) {\n\t\t\tresult[length] = fn(array[length]);\n\t\t}\n\t\treturn result;\n\t}\n\n\t/**\n\t * A simple `Array#map`-like wrapper to work with domain name strings or email\n\t * addresses.\n\t * @private\n\t * @param {String} domain The domain name or email address.\n\t * @param {Function} callback The function that gets called for every\n\t * character.\n\t * @returns {Array} A new string of characters returned by the callback\n\t * function.\n\t */\n\tfunction mapDomain(string, fn) {\n\t\tvar parts = string.split('@');\n\t\tvar result = '';\n\t\tif (parts.length > 1) {\n\t\t\t// In email addresses, only the domain name should be punycoded. Leave\n\t\t\t// the local part (i.e. everything up to `@`) intact.\n\t\t\tresult = parts[0] + '@';\n\t\t\tstring = parts[1];\n\t\t}\n\t\t// Avoid `split(regex)` for IE8 compatibility. See #17.\n\t\tstring = string.replace(regexSeparators, '\\x2E');\n\t\tvar labels = string.split('.');\n\t\tvar encoded = map(labels, fn).join('.');\n\t\treturn result + encoded;\n\t}\n\n\t/**\n\t * Creates an array containing the numeric code points of each Unicode\n\t * character in the string. While JavaScript uses UCS-2 internally,\n\t * this function will convert a pair of surrogate halves (each of which\n\t * UCS-2 exposes as separate characters) into a single code point,\n\t * matching UTF-16.\n\t * @see `punycode.ucs2.encode`\n\t * @see \n\t * @memberOf punycode.ucs2\n\t * @name decode\n\t * @param {String} string The Unicode input string (UCS-2).\n\t * @returns {Array} The new array of code points.\n\t */\n\tfunction ucs2decode(string) {\n\t\tvar output = [],\n\t\t counter = 0,\n\t\t length = string.length,\n\t\t value,\n\t\t extra;\n\t\twhile (counter < length) {\n\t\t\tvalue = string.charCodeAt(counter++);\n\t\t\tif (value >= 0xD800 && value <= 0xDBFF && counter < length) {\n\t\t\t\t// high surrogate, and there is a next character\n\t\t\t\textra = string.charCodeAt(counter++);\n\t\t\t\tif ((extra & 0xFC00) == 0xDC00) { // low surrogate\n\t\t\t\t\toutput.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);\n\t\t\t\t} else {\n\t\t\t\t\t// unmatched surrogate; only append this code unit, in case the next\n\t\t\t\t\t// code unit is the high surrogate of a surrogate pair\n\t\t\t\t\toutput.push(value);\n\t\t\t\t\tcounter--;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\toutput.push(value);\n\t\t\t}\n\t\t}\n\t\treturn output;\n\t}\n\n\t/**\n\t * Creates a string based on an array of numeric code points.\n\t * @see `punycode.ucs2.decode`\n\t * @memberOf punycode.ucs2\n\t * @name encode\n\t * @param {Array} codePoints The array of numeric code points.\n\t * @returns {String} The new Unicode string (UCS-2).\n\t */\n\tfunction ucs2encode(array) {\n\t\treturn map(array, function(value) {\n\t\t\tvar output = '';\n\t\t\tif (value > 0xFFFF) {\n\t\t\t\tvalue -= 0x10000;\n\t\t\t\toutput += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);\n\t\t\t\tvalue = 0xDC00 | value & 0x3FF;\n\t\t\t}\n\t\t\toutput += stringFromCharCode(value);\n\t\t\treturn output;\n\t\t}).join('');\n\t}\n\n\t/**\n\t * Converts a basic code point into a digit/integer.\n\t * @see `digitToBasic()`\n\t * @private\n\t * @param {Number} codePoint The basic numeric code point value.\n\t * @returns {Number} The numeric value of a basic code point (for use in\n\t * representing integers) in the range `0` to `base - 1`, or `base` if\n\t * the code point does not represent a value.\n\t */\n\tfunction basicToDigit(codePoint) {\n\t\tif (codePoint - 48 < 10) {\n\t\t\treturn codePoint - 22;\n\t\t}\n\t\tif (codePoint - 65 < 26) {\n\t\t\treturn codePoint - 65;\n\t\t}\n\t\tif (codePoint - 97 < 26) {\n\t\t\treturn codePoint - 97;\n\t\t}\n\t\treturn base;\n\t}\n\n\t/**\n\t * Converts a digit/integer into a basic code point.\n\t * @see `basicToDigit()`\n\t * @private\n\t * @param {Number} digit The numeric value of a basic code point.\n\t * @returns {Number} The basic code point whose value (when used for\n\t * representing integers) is `digit`, which needs to be in the range\n\t * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is\n\t * used; else, the lowercase form is used. The behavior is undefined\n\t * if `flag` is non-zero and `digit` has no uppercase form.\n\t */\n\tfunction digitToBasic(digit, flag) {\n\t\t// 0..25 map to ASCII a..z or A..Z\n\t\t// 26..35 map to ASCII 0..9\n\t\treturn digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);\n\t}\n\n\t/**\n\t * Bias adaptation function as per section 3.4 of RFC 3492.\n\t * https://tools.ietf.org/html/rfc3492#section-3.4\n\t * @private\n\t */\n\tfunction adapt(delta, numPoints, firstTime) {\n\t\tvar k = 0;\n\t\tdelta = firstTime ? floor(delta / damp) : delta >> 1;\n\t\tdelta += floor(delta / numPoints);\n\t\tfor (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {\n\t\t\tdelta = floor(delta / baseMinusTMin);\n\t\t}\n\t\treturn floor(k + (baseMinusTMin + 1) * delta / (delta + skew));\n\t}\n\n\t/**\n\t * Converts a Punycode string of ASCII-only symbols to a string of Unicode\n\t * symbols.\n\t * @memberOf punycode\n\t * @param {String} input The Punycode string of ASCII-only symbols.\n\t * @returns {String} The resulting string of Unicode symbols.\n\t */\n\tfunction decode(input) {\n\t\t// Don't use UCS-2\n\t\tvar output = [],\n\t\t inputLength = input.length,\n\t\t out,\n\t\t i = 0,\n\t\t n = initialN,\n\t\t bias = initialBias,\n\t\t basic,\n\t\t j,\n\t\t index,\n\t\t oldi,\n\t\t w,\n\t\t k,\n\t\t digit,\n\t\t t,\n\t\t /** Cached calculation results */\n\t\t baseMinusT;\n\n\t\t// Handle the basic code points: let `basic` be the number of input code\n\t\t// points before the last delimiter, or `0` if there is none, then copy\n\t\t// the first basic code points to the output.\n\n\t\tbasic = input.lastIndexOf(delimiter);\n\t\tif (basic < 0) {\n\t\t\tbasic = 0;\n\t\t}\n\n\t\tfor (j = 0; j < basic; ++j) {\n\t\t\t// if it's not a basic code point\n\t\t\tif (input.charCodeAt(j) >= 0x80) {\n\t\t\t\terror('not-basic');\n\t\t\t}\n\t\t\toutput.push(input.charCodeAt(j));\n\t\t}\n\n\t\t// Main decoding loop: start just after the last delimiter if any basic code\n\t\t// points were copied; start at the beginning otherwise.\n\n\t\tfor (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {\n\n\t\t\t// `index` is the index of the next character to be consumed.\n\t\t\t// Decode a generalized variable-length integer into `delta`,\n\t\t\t// which gets added to `i`. The overflow checking is easier\n\t\t\t// if we increase `i` as we go, then subtract off its starting\n\t\t\t// value at the end to obtain `delta`.\n\t\t\tfor (oldi = i, w = 1, k = base; /* no condition */; k += base) {\n\n\t\t\t\tif (index >= inputLength) {\n\t\t\t\t\terror('invalid-input');\n\t\t\t\t}\n\n\t\t\t\tdigit = basicToDigit(input.charCodeAt(index++));\n\n\t\t\t\tif (digit >= base || digit > floor((maxInt - i) / w)) {\n\t\t\t\t\terror('overflow');\n\t\t\t\t}\n\n\t\t\t\ti += digit * w;\n\t\t\t\tt = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);\n\n\t\t\t\tif (digit < t) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tbaseMinusT = base - t;\n\t\t\t\tif (w > floor(maxInt / baseMinusT)) {\n\t\t\t\t\terror('overflow');\n\t\t\t\t}\n\n\t\t\t\tw *= baseMinusT;\n\n\t\t\t}\n\n\t\t\tout = output.length + 1;\n\t\t\tbias = adapt(i - oldi, out, oldi == 0);\n\n\t\t\t// `i` was supposed to wrap around from `out` to `0`,\n\t\t\t// incrementing `n` each time, so we'll fix that now:\n\t\t\tif (floor(i / out) > maxInt - n) {\n\t\t\t\terror('overflow');\n\t\t\t}\n\n\t\t\tn += floor(i / out);\n\t\t\ti %= out;\n\n\t\t\t// Insert `n` at position `i` of the output\n\t\t\toutput.splice(i++, 0, n);\n\n\t\t}\n\n\t\treturn ucs2encode(output);\n\t}\n\n\t/**\n\t * Converts a string of Unicode symbols (e.g. a domain name label) to a\n\t * Punycode string of ASCII-only symbols.\n\t * @memberOf punycode\n\t * @param {String} input The string of Unicode symbols.\n\t * @returns {String} The resulting Punycode string of ASCII-only symbols.\n\t */\n\tfunction encode(input) {\n\t\tvar n,\n\t\t delta,\n\t\t handledCPCount,\n\t\t basicLength,\n\t\t bias,\n\t\t j,\n\t\t m,\n\t\t q,\n\t\t k,\n\t\t t,\n\t\t currentValue,\n\t\t output = [],\n\t\t /** `inputLength` will hold the number of code points in `input`. */\n\t\t inputLength,\n\t\t /** Cached calculation results */\n\t\t handledCPCountPlusOne,\n\t\t baseMinusT,\n\t\t qMinusT;\n\n\t\t// Convert the input in UCS-2 to Unicode\n\t\tinput = ucs2decode(input);\n\n\t\t// Cache the length\n\t\tinputLength = input.length;\n\n\t\t// Initialize the state\n\t\tn = initialN;\n\t\tdelta = 0;\n\t\tbias = initialBias;\n\n\t\t// Handle the basic code points\n\t\tfor (j = 0; j < inputLength; ++j) {\n\t\t\tcurrentValue = input[j];\n\t\t\tif (currentValue < 0x80) {\n\t\t\t\toutput.push(stringFromCharCode(currentValue));\n\t\t\t}\n\t\t}\n\n\t\thandledCPCount = basicLength = output.length;\n\n\t\t// `handledCPCount` is the number of code points that have been handled;\n\t\t// `basicLength` is the number of basic code points.\n\n\t\t// Finish the basic string - if it is not empty - with a delimiter\n\t\tif (basicLength) {\n\t\t\toutput.push(delimiter);\n\t\t}\n\n\t\t// Main encoding loop:\n\t\twhile (handledCPCount < inputLength) {\n\n\t\t\t// All non-basic code points < n have been handled already. Find the next\n\t\t\t// larger one:\n\t\t\tfor (m = maxInt, j = 0; j < inputLength; ++j) {\n\t\t\t\tcurrentValue = input[j];\n\t\t\t\tif (currentValue >= n && currentValue < m) {\n\t\t\t\t\tm = currentValue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Increase `delta` enough to advance the decoder's state to ,\n\t\t\t// but guard against overflow\n\t\t\thandledCPCountPlusOne = handledCPCount + 1;\n\t\t\tif (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {\n\t\t\t\terror('overflow');\n\t\t\t}\n\n\t\t\tdelta += (m - n) * handledCPCountPlusOne;\n\t\t\tn = m;\n\n\t\t\tfor (j = 0; j < inputLength; ++j) {\n\t\t\t\tcurrentValue = input[j];\n\n\t\t\t\tif (currentValue < n && ++delta > maxInt) {\n\t\t\t\t\terror('overflow');\n\t\t\t\t}\n\n\t\t\t\tif (currentValue == n) {\n\t\t\t\t\t// Represent delta as a generalized variable-length integer\n\t\t\t\t\tfor (q = delta, k = base; /* no condition */; k += base) {\n\t\t\t\t\t\tt = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);\n\t\t\t\t\t\tif (q < t) {\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tqMinusT = q - t;\n\t\t\t\t\t\tbaseMinusT = base - t;\n\t\t\t\t\t\toutput.push(\n\t\t\t\t\t\t\tstringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))\n\t\t\t\t\t\t);\n\t\t\t\t\t\tq = floor(qMinusT / baseMinusT);\n\t\t\t\t\t}\n\n\t\t\t\t\toutput.push(stringFromCharCode(digitToBasic(q, 0)));\n\t\t\t\t\tbias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);\n\t\t\t\t\tdelta = 0;\n\t\t\t\t\t++handledCPCount;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t++delta;\n\t\t\t++n;\n\n\t\t}\n\t\treturn output.join('');\n\t}\n\n\t/**\n\t * Converts a Punycode string representing a domain name or an email address\n\t * to Unicode. Only the Punycoded parts of the input will be converted, i.e.\n\t * it doesn't matter if you call it on a string that has already been\n\t * converted to Unicode.\n\t * @memberOf punycode\n\t * @param {String} input The Punycoded domain name or email address to\n\t * convert to Unicode.\n\t * @returns {String} The Unicode representation of the given Punycode\n\t * string.\n\t */\n\tfunction toUnicode(input) {\n\t\treturn mapDomain(input, function(string) {\n\t\t\treturn regexPunycode.test(string)\n\t\t\t\t? decode(string.slice(4).toLowerCase())\n\t\t\t\t: string;\n\t\t});\n\t}\n\n\t/**\n\t * Converts a Unicode string representing a domain name or an email address to\n\t * Punycode. Only the non-ASCII parts of the domain name will be converted,\n\t * i.e. it doesn't matter if you call it with a domain that's already in\n\t * ASCII.\n\t * @memberOf punycode\n\t * @param {String} input The domain name or email address to convert, as a\n\t * Unicode string.\n\t * @returns {String} The Punycode representation of the given domain name or\n\t * email address.\n\t */\n\tfunction toASCII(input) {\n\t\treturn mapDomain(input, function(string) {\n\t\t\treturn regexNonASCII.test(string)\n\t\t\t\t? 'xn--' + encode(string)\n\t\t\t\t: string;\n\t\t});\n\t}\n\n\t/*--------------------------------------------------------------------------*/\n\n\t/** Define the public API */\n\tpunycode = {\n\t\t/**\n\t\t * A string representing the current Punycode.js version number.\n\t\t * @memberOf punycode\n\t\t * @type String\n\t\t */\n\t\t'version': '1.3.2',\n\t\t/**\n\t\t * An object of methods to convert from JavaScript's internal character\n\t\t * representation (UCS-2) to Unicode code points, and back.\n\t\t * @see \n\t\t * @memberOf punycode\n\t\t * @type Object\n\t\t */\n\t\t'ucs2': {\n\t\t\t'decode': ucs2decode,\n\t\t\t'encode': ucs2encode\n\t\t},\n\t\t'decode': decode,\n\t\t'encode': encode,\n\t\t'toASCII': toASCII,\n\t\t'toUnicode': toUnicode\n\t};\n\n\t/** Expose `punycode` */\n\t// Some AMD build optimizers, like r.js, check for specific condition patterns\n\t// like the following:\n\tif (\n\t\ttypeof define == 'function' &&\n\t\ttypeof define.amd == 'object' &&\n\t\tdefine.amd\n\t) {\n\t\tdefine('punycode', function() {\n\t\t\treturn punycode;\n\t\t});\n\t} else if (freeExports && freeModule) {\n\t\tif (module.exports == freeExports) {\n\t\t\t// in Node.js, io.js, or RingoJS v0.8.0+\n\t\t\tfreeModule.exports = punycode;\n\t\t} else {\n\t\t\t// in Narwhal or RingoJS v0.7.0-\n\t\t\tfor (key in punycode) {\n\t\t\t\tpunycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// in Rhino or a web browser\n\t\troot.punycode = punycode;\n\t}\n\n}(this));\n", "/*!\n * URI.js - Mutating URLs\n * IPv6 Support\n *\n * Version: 1.19.11\n *\n * Author: Rodney Rehm\n * Web: http://medialize.github.io/URI.js/\n *\n * Licensed under\n * MIT License http://www.opensource.org/licenses/mit-license\n *\n */\n\n(function (root, factory) {\n 'use strict';\n // https://github.com/umdjs/umd/blob/master/returnExports.js\n if (typeof module === 'object' && module.exports) {\n // Node\n module.exports = factory();\n } else if (typeof define === 'function' && define.amd) {\n // AMD. Register as an anonymous module.\n define(factory);\n } else {\n // Browser globals (root is window)\n root.IPv6 = factory(root);\n }\n}(this, function (root) {\n 'use strict';\n\n /*\n var _in = \"fe80:0000:0000:0000:0204:61ff:fe9d:f156\";\n var _out = IPv6.best(_in);\n var _expected = \"fe80::204:61ff:fe9d:f156\";\n\n console.log(_in, _out, _expected, _out === _expected);\n */\n\n // save current IPv6 variable, if any\n var _IPv6 = root && root.IPv6;\n\n function bestPresentation(address) {\n // based on:\n // Javascript to test an IPv6 address for proper format, and to\n // present the \"best text representation\" according to IETF Draft RFC at\n // http://tools.ietf.org/html/draft-ietf-6man-text-addr-representation-04\n // 8 Feb 2010 Rich Brown, Dartware, LLC\n // Please feel free to use this code as long as you provide a link to\n // http://www.intermapper.com\n // http://intermapper.com/support/tools/IPV6-Validator.aspx\n // http://download.dartware.com/thirdparty/ipv6validator.js\n\n var _address = address.toLowerCase();\n var segments = _address.split(':');\n var length = segments.length;\n var total = 8;\n\n // trim colons (:: or ::a:b:c\u2026 or \u2026a:b:c::)\n if (segments[0] === '' && segments[1] === '' && segments[2] === '') {\n // must have been ::\n // remove first two items\n segments.shift();\n segments.shift();\n } else if (segments[0] === '' && segments[1] === '') {\n // must have been ::xxxx\n // remove the first item\n segments.shift();\n } else if (segments[length - 1] === '' && segments[length - 2] === '') {\n // must have been xxxx::\n segments.pop();\n }\n\n length = segments.length;\n\n // adjust total segments for IPv4 trailer\n if (segments[length - 1].indexOf('.') !== -1) {\n // found a \".\" which means IPv4\n total = 7;\n }\n\n // fill empty segments them with \"0000\"\n var pos;\n for (pos = 0; pos < length; pos++) {\n if (segments[pos] === '') {\n break;\n }\n }\n\n if (pos < total) {\n segments.splice(pos, 1, '0000');\n while (segments.length < total) {\n segments.splice(pos, 0, '0000');\n }\n }\n\n // strip leading zeros\n var _segments;\n for (var i = 0; i < total; i++) {\n _segments = segments[i].split('');\n for (var j = 0; j < 3 ; j++) {\n if (_segments[0] === '0' && _segments.length > 1) {\n _segments.splice(0,1);\n } else {\n break;\n }\n }\n\n segments[i] = _segments.join('');\n }\n\n // find longest sequence of zeroes and coalesce them into one segment\n var best = -1;\n var _best = 0;\n var _current = 0;\n var current = -1;\n var inzeroes = false;\n // i; already declared\n\n for (i = 0; i < total; i++) {\n if (inzeroes) {\n if (segments[i] === '0') {\n _current += 1;\n } else {\n inzeroes = false;\n if (_current > _best) {\n best = current;\n _best = _current;\n }\n }\n } else {\n if (segments[i] === '0') {\n inzeroes = true;\n current = i;\n _current = 1;\n }\n }\n }\n\n if (_current > _best) {\n best = current;\n _best = _current;\n }\n\n if (_best > 1) {\n segments.splice(best, _best, '');\n }\n\n length = segments.length;\n\n // assemble remaining segments\n var result = '';\n if (segments[0] === '') {\n result = ':';\n }\n\n for (i = 0; i < length; i++) {\n result += segments[i];\n if (i === length - 1) {\n break;\n }\n\n result += ':';\n }\n\n if (segments[length - 1] === '') {\n result += ':';\n }\n\n return result;\n }\n\n function noConflict() {\n /*jshint validthis: true */\n if (root.IPv6 === this) {\n root.IPv6 = _IPv6;\n }\n\n return this;\n }\n\n return {\n best: bestPresentation,\n noConflict: noConflict\n };\n}));\n", "/*!\n * URI.js - Mutating URLs\n * Second Level Domain (SLD) Support\n *\n * Version: 1.19.11\n *\n * Author: Rodney Rehm\n * Web: http://medialize.github.io/URI.js/\n *\n * Licensed under\n * MIT License http://www.opensource.org/licenses/mit-license\n *\n */\n\n(function (root, factory) {\n 'use strict';\n // https://github.com/umdjs/umd/blob/master/returnExports.js\n if (typeof module === 'object' && module.exports) {\n // Node\n module.exports = factory();\n } else if (typeof define === 'function' && define.amd) {\n // AMD. Register as an anonymous module.\n define(factory);\n } else {\n // Browser globals (root is window)\n root.SecondLevelDomains = factory(root);\n }\n}(this, function (root) {\n 'use strict';\n\n // save current SecondLevelDomains variable, if any\n var _SecondLevelDomains = root && root.SecondLevelDomains;\n\n var SLD = {\n // list of known Second Level Domains\n // converted list of SLDs from https://github.com/gavingmiller/second-level-domains\n // ----\n // publicsuffix.org is more current and actually used by a couple of browsers internally.\n // downside is it also contains domains like \"dyndns.org\" - which is fine for the security\n // issues browser have to deal with (SOP for cookies, etc) - but is way overboard for URI.js\n // ----\n list: {\n 'ac':' com gov mil net org ',\n 'ae':' ac co gov mil name net org pro sch ',\n 'af':' com edu gov net org ',\n 'al':' com edu gov mil net org ',\n 'ao':' co ed gv it og pb ',\n 'ar':' com edu gob gov int mil net org tur ',\n 'at':' ac co gv or ',\n 'au':' asn com csiro edu gov id net org ',\n 'ba':' co com edu gov mil net org rs unbi unmo unsa untz unze ',\n 'bb':' biz co com edu gov info net org store tv ',\n 'bh':' biz cc com edu gov info net org ',\n 'bn':' com edu gov net org ',\n 'bo':' com edu gob gov int mil net org tv ',\n 'br':' adm adv agr am arq art ato b bio blog bmd cim cng cnt com coop ecn edu eng esp etc eti far flog fm fnd fot fst g12 ggf gov imb ind inf jor jus lel mat med mil mus net nom not ntr odo org ppg pro psc psi qsl rec slg srv tmp trd tur tv vet vlog wiki zlg ',\n 'bs':' com edu gov net org ',\n 'bz':' du et om ov rg ',\n 'ca':' ab bc mb nb nf nl ns nt nu on pe qc sk yk ',\n 'ck':' biz co edu gen gov info net org ',\n 'cn':' ac ah bj com cq edu fj gd gov gs gx gz ha hb he hi hl hn jl js jx ln mil net nm nx org qh sc sd sh sn sx tj tw xj xz yn zj ',\n 'co':' com edu gov mil net nom org ',\n 'cr':' ac c co ed fi go or sa ',\n 'cy':' ac biz com ekloges gov ltd name net org parliament press pro tm ',\n 'do':' art com edu gob gov mil net org sld web ',\n 'dz':' art asso com edu gov net org pol ',\n 'ec':' com edu fin gov info med mil net org pro ',\n 'eg':' com edu eun gov mil name net org sci ',\n 'er':' com edu gov ind mil net org rochest w ',\n 'es':' com edu gob nom org ',\n 'et':' biz com edu gov info name net org ',\n 'fj':' ac biz com info mil name net org pro ',\n 'fk':' ac co gov net nom org ',\n 'fr':' asso com f gouv nom prd presse tm ',\n 'gg':' co net org ',\n 'gh':' com edu gov mil org ',\n 'gn':' ac com gov net org ',\n 'gr':' com edu gov mil net org ',\n 'gt':' com edu gob ind mil net org ',\n 'gu':' com edu gov net org ',\n 'hk':' com edu gov idv net org ',\n 'hu':' 2000 agrar bolt casino city co erotica erotika film forum games hotel info ingatlan jogasz konyvelo lakas media news org priv reklam sex shop sport suli szex tm tozsde utazas video ',\n 'id':' ac co go mil net or sch web ',\n 'il':' ac co gov idf k12 muni net org ',\n 'in':' ac co edu ernet firm gen gov i ind mil net nic org res ',\n 'iq':' com edu gov i mil net org ',\n 'ir':' ac co dnssec gov i id net org sch ',\n 'it':' edu gov ',\n 'je':' co net org ',\n 'jo':' com edu gov mil name net org sch ',\n 'jp':' ac ad co ed go gr lg ne or ',\n 'ke':' ac co go info me mobi ne or sc ',\n 'kh':' com edu gov mil net org per ',\n 'ki':' biz com de edu gov info mob net org tel ',\n 'km':' asso com coop edu gouv k medecin mil nom notaires pharmaciens presse tm veterinaire ',\n 'kn':' edu gov net org ',\n 'kr':' ac busan chungbuk chungnam co daegu daejeon es gangwon go gwangju gyeongbuk gyeonggi gyeongnam hs incheon jeju jeonbuk jeonnam k kg mil ms ne or pe re sc seoul ulsan ',\n 'kw':' com edu gov net org ',\n 'ky':' com edu gov net org ',\n 'kz':' com edu gov mil net org ',\n 'lb':' com edu gov net org ',\n 'lk':' assn com edu gov grp hotel int ltd net ngo org sch soc web ',\n 'lr':' com edu gov net org ',\n 'lv':' asn com conf edu gov id mil net org ',\n 'ly':' com edu gov id med net org plc sch ',\n 'ma':' ac co gov m net org press ',\n 'mc':' asso tm ',\n 'me':' ac co edu gov its net org priv ',\n 'mg':' com edu gov mil nom org prd tm ',\n 'mk':' com edu gov inf name net org pro ',\n 'ml':' com edu gov net org presse ',\n 'mn':' edu gov org ',\n 'mo':' com edu gov net org ',\n 'mt':' com edu gov net org ',\n 'mv':' aero biz com coop edu gov info int mil museum name net org pro ',\n 'mw':' ac co com coop edu gov int museum net org ',\n 'mx':' com edu gob net org ',\n 'my':' com edu gov mil name net org sch ',\n 'nf':' arts com firm info net other per rec store web ',\n 'ng':' biz com edu gov mil mobi name net org sch ',\n 'ni':' ac co com edu gob mil net nom org ',\n 'np':' com edu gov mil net org ',\n 'nr':' biz com edu gov info net org ',\n 'om':' ac biz co com edu gov med mil museum net org pro sch ',\n 'pe':' com edu gob mil net nom org sld ',\n 'ph':' com edu gov i mil net ngo org ',\n 'pk':' biz com edu fam gob gok gon gop gos gov net org web ',\n 'pl':' art bialystok biz com edu gda gdansk gorzow gov info katowice krakow lodz lublin mil net ngo olsztyn org poznan pwr radom slupsk szczecin torun warszawa waw wroc wroclaw zgora ',\n 'pr':' ac biz com edu est gov info isla name net org pro prof ',\n 'ps':' com edu gov net org plo sec ',\n 'pw':' belau co ed go ne or ',\n 'ro':' arts com firm info nom nt org rec store tm www ',\n 'rs':' ac co edu gov in org ',\n 'sb':' com edu gov net org ',\n 'sc':' com edu gov net org ',\n 'sh':' co com edu gov net nom org ',\n 'sl':' com edu gov net org ',\n 'st':' co com consulado edu embaixada gov mil net org principe saotome store ',\n 'sv':' com edu gob org red ',\n 'sz':' ac co org ',\n 'tr':' av bbs bel biz com dr edu gen gov info k12 name net org pol tel tsk tv web ',\n 'tt':' aero biz cat co com coop edu gov info int jobs mil mobi museum name net org pro tel travel ',\n 'tw':' club com ebiz edu game gov idv mil net org ',\n 'mu':' ac co com gov net or org ',\n 'mz':' ac co edu gov org ',\n 'na':' co com ',\n 'nz':' ac co cri geek gen govt health iwi maori mil net org parliament school ',\n 'pa':' abo ac com edu gob ing med net nom org sld ',\n 'pt':' com edu gov int net nome org publ ',\n 'py':' com edu gov mil net org ',\n 'qa':' com edu gov mil net org ',\n 're':' asso com nom ',\n 'ru':' ac adygeya altai amur arkhangelsk astrakhan bashkiria belgorod bir bryansk buryatia cbg chel chelyabinsk chita chukotka chuvashia com dagestan e-burg edu gov grozny int irkutsk ivanovo izhevsk jar joshkar-ola kalmykia kaluga kamchatka karelia kazan kchr kemerovo khabarovsk khakassia khv kirov koenig komi kostroma kranoyarsk kuban kurgan kursk lipetsk magadan mari mari-el marine mil mordovia mosreg msk murmansk nalchik net nnov nov novosibirsk nsk omsk orenburg org oryol penza perm pp pskov ptz rnd ryazan sakhalin samara saratov simbirsk smolensk spb stavropol stv surgut tambov tatarstan tom tomsk tsaritsyn tsk tula tuva tver tyumen udm udmurtia ulan-ude vladikavkaz vladimir vladivostok volgograd vologda voronezh vrn vyatka yakutia yamal yekaterinburg yuzhno-sakhalinsk ',\n 'rw':' ac co com edu gouv gov int mil net ',\n 'sa':' com edu gov med net org pub sch ',\n 'sd':' com edu gov info med net org tv ',\n 'se':' a ac b bd c d e f g h i k l m n o org p parti pp press r s t tm u w x y z ',\n 'sg':' com edu gov idn net org per ',\n 'sn':' art com edu gouv org perso univ ',\n 'sy':' com edu gov mil net news org ',\n 'th':' ac co go in mi net or ',\n 'tj':' ac biz co com edu go gov info int mil name net nic org test web ',\n 'tn':' agrinet com defense edunet ens fin gov ind info intl mincom nat net org perso rnrt rns rnu tourism ',\n 'tz':' ac co go ne or ',\n 'ua':' biz cherkassy chernigov chernovtsy ck cn co com crimea cv dn dnepropetrovsk donetsk dp edu gov if in ivano-frankivsk kh kharkov kherson khmelnitskiy kiev kirovograd km kr ks kv lg lugansk lutsk lviv me mk net nikolaev od odessa org pl poltava pp rovno rv sebastopol sumy te ternopil uzhgorod vinnica vn zaporizhzhe zhitomir zp zt ',\n 'ug':' ac co go ne or org sc ',\n 'uk':' ac bl british-library co cym gov govt icnet jet lea ltd me mil mod national-library-scotland nel net nhs nic nls org orgn parliament plc police sch scot soc ',\n 'us':' dni fed isa kids nsn ',\n 'uy':' com edu gub mil net org ',\n 've':' co com edu gob info mil net org web ',\n 'vi':' co com k12 net org ',\n 'vn':' ac biz com edu gov health info int name net org pro ',\n 'ye':' co com gov ltd me net org plc ',\n 'yu':' ac co edu gov org ',\n 'za':' ac agric alt bourse city co cybernet db edu gov grondar iaccess imt inca landesign law mil net ngo nis nom olivetti org pix school tm web ',\n 'zm':' ac co com edu gov net org sch ',\n // https://en.wikipedia.org/wiki/CentralNic#Second-level_domains\n 'com': 'ar br cn de eu gb gr hu jpn kr no qc ru sa se uk us uy za ',\n 'net': 'gb jp se uk ',\n 'org': 'ae',\n 'de': 'com '\n },\n // gorhill 2013-10-25: Using indexOf() instead Regexp(). Significant boost\n // in both performance and memory footprint. No initialization required.\n // http://jsperf.com/uri-js-sld-regex-vs-binary-search/4\n // Following methods use lastIndexOf() rather than array.split() in order\n // to avoid any memory allocations.\n has: function(domain) {\n var tldOffset = domain.lastIndexOf('.');\n if (tldOffset <= 0 || tldOffset >= (domain.length-1)) {\n return false;\n }\n var sldOffset = domain.lastIndexOf('.', tldOffset-1);\n if (sldOffset <= 0 || sldOffset >= (tldOffset-1)) {\n return false;\n }\n var sldList = SLD.list[domain.slice(tldOffset+1)];\n if (!sldList) {\n return false;\n }\n return sldList.indexOf(' ' + domain.slice(sldOffset+1, tldOffset) + ' ') >= 0;\n },\n is: function(domain) {\n var tldOffset = domain.lastIndexOf('.');\n if (tldOffset <= 0 || tldOffset >= (domain.length-1)) {\n return false;\n }\n var sldOffset = domain.lastIndexOf('.', tldOffset-1);\n if (sldOffset >= 0) {\n return false;\n }\n var sldList = SLD.list[domain.slice(tldOffset+1)];\n if (!sldList) {\n return false;\n }\n return sldList.indexOf(' ' + domain.slice(0, tldOffset) + ' ') >= 0;\n },\n get: function(domain) {\n var tldOffset = domain.lastIndexOf('.');\n if (tldOffset <= 0 || tldOffset >= (domain.length-1)) {\n return null;\n }\n var sldOffset = domain.lastIndexOf('.', tldOffset-1);\n if (sldOffset <= 0 || sldOffset >= (tldOffset-1)) {\n return null;\n }\n var sldList = SLD.list[domain.slice(tldOffset+1)];\n if (!sldList) {\n return null;\n }\n if (sldList.indexOf(' ' + domain.slice(sldOffset+1, tldOffset) + ' ') < 0) {\n return null;\n }\n return domain.slice(sldOffset+1);\n },\n noConflict: function(){\n if (root.SecondLevelDomains === this) {\n root.SecondLevelDomains = _SecondLevelDomains;\n }\n return this;\n }\n };\n\n return SLD;\n}));\n", "/*!\n * URI.js - Mutating URLs\n *\n * Version: 1.19.11\n *\n * Author: Rodney Rehm\n * Web: http://medialize.github.io/URI.js/\n *\n * Licensed under\n * MIT License http://www.opensource.org/licenses/mit-license\n *\n */\n(function (root, factory) {\n 'use strict';\n // https://github.com/umdjs/umd/blob/master/returnExports.js\n if (typeof module === 'object' && module.exports) {\n // Node\n module.exports = factory(require('./punycode'), require('./IPv6'), require('./SecondLevelDomains'));\n } else if (typeof define === 'function' && define.amd) {\n // AMD. Register as an anonymous module.\n define(['./punycode', './IPv6', './SecondLevelDomains'], factory);\n } else {\n // Browser globals (root is window)\n root.URI = factory(root.punycode, root.IPv6, root.SecondLevelDomains, root);\n }\n}(this, function (punycode, IPv6, SLD, root) {\n 'use strict';\n /*global location, escape, unescape */\n // FIXME: v2.0.0 renamce non-camelCase properties to uppercase\n /*jshint camelcase: false */\n\n // save current URI variable, if any\n var _URI = root && root.URI;\n\n function URI(url, base) {\n var _urlSupplied = arguments.length >= 1;\n var _baseSupplied = arguments.length >= 2;\n\n // Allow instantiation without the 'new' keyword\n if (!(this instanceof URI)) {\n if (_urlSupplied) {\n if (_baseSupplied) {\n return new URI(url, base);\n }\n\n return new URI(url);\n }\n\n return new URI();\n }\n\n if (url === undefined) {\n if (_urlSupplied) {\n throw new TypeError('undefined is not a valid argument for URI');\n }\n\n if (typeof location !== 'undefined') {\n url = location.href + '';\n } else {\n url = '';\n }\n }\n\n if (url === null) {\n if (_urlSupplied) {\n throw new TypeError('null is not a valid argument for URI');\n }\n }\n\n this.href(url);\n\n // resolve to base according to http://dvcs.w3.org/hg/url/raw-file/tip/Overview.html#constructor\n if (base !== undefined) {\n return this.absoluteTo(base);\n }\n\n return this;\n }\n\n function isInteger(value) {\n return /^[0-9]+$/.test(value);\n }\n\n URI.version = '1.19.11';\n\n var p = URI.prototype;\n var hasOwn = Object.prototype.hasOwnProperty;\n\n function escapeRegEx(string) {\n // https://github.com/medialize/URI.js/commit/85ac21783c11f8ccab06106dba9735a31a86924d#commitcomment-821963\n return string.replace(/([.*+?^=!:${}()|[\\]\\/\\\\])/g, '\\\\$1');\n }\n\n function getType(value) {\n // IE8 doesn't return [Object Undefined] but [Object Object] for undefined value\n if (value === undefined) {\n return 'Undefined';\n }\n\n return String(Object.prototype.toString.call(value)).slice(8, -1);\n }\n\n function isArray(obj) {\n return getType(obj) === 'Array';\n }\n\n function filterArrayValues(data, value) {\n var lookup = {};\n var i, length;\n\n if (getType(value) === 'RegExp') {\n lookup = null;\n } else if (isArray(value)) {\n for (i = 0, length = value.length; i < length; i++) {\n lookup[value[i]] = true;\n }\n } else {\n lookup[value] = true;\n }\n\n for (i = 0, length = data.length; i < length; i++) {\n /*jshint laxbreak: true */\n var _match = lookup && lookup[data[i]] !== undefined\n || !lookup && value.test(data[i]);\n /*jshint laxbreak: false */\n if (_match) {\n data.splice(i, 1);\n length--;\n i--;\n }\n }\n\n return data;\n }\n\n function arrayContains(list, value) {\n var i, length;\n\n // value may be string, number, array, regexp\n if (isArray(value)) {\n // Note: this can be optimized to O(n) (instead of current O(m * n))\n for (i = 0, length = value.length; i < length; i++) {\n if (!arrayContains(list, value[i])) {\n return false;\n }\n }\n\n return true;\n }\n\n var _type = getType(value);\n for (i = 0, length = list.length; i < length; i++) {\n if (_type === 'RegExp') {\n if (typeof list[i] === 'string' && list[i].match(value)) {\n return true;\n }\n } else if (list[i] === value) {\n return true;\n }\n }\n\n return false;\n }\n\n function arraysEqual(one, two) {\n if (!isArray(one) || !isArray(two)) {\n return false;\n }\n\n // arrays can't be equal if they have different amount of content\n if (one.length !== two.length) {\n return false;\n }\n\n one.sort();\n two.sort();\n\n for (var i = 0, l = one.length; i < l; i++) {\n if (one[i] !== two[i]) {\n return false;\n }\n }\n\n return true;\n }\n\n function trimSlashes(text) {\n var trim_expression = /^\\/+|\\/+$/g;\n return text.replace(trim_expression, '');\n }\n\n URI._parts = function() {\n return {\n protocol: null,\n username: null,\n password: null,\n hostname: null,\n urn: null,\n port: null,\n path: null,\n query: null,\n fragment: null,\n // state\n preventInvalidHostname: URI.preventInvalidHostname,\n duplicateQueryParameters: URI.duplicateQueryParameters,\n escapeQuerySpace: URI.escapeQuerySpace\n };\n };\n // state: throw on invalid hostname\n // see https://github.com/medialize/URI.js/pull/345\n // and https://github.com/medialize/URI.js/issues/354\n URI.preventInvalidHostname = false;\n // state: allow duplicate query parameters (a=1&a=1)\n URI.duplicateQueryParameters = false;\n // state: replaces + with %20 (space in query strings)\n URI.escapeQuerySpace = true;\n // static properties\n URI.protocol_expression = /^[a-z][a-z0-9.+-]*$/i;\n URI.idn_expression = /[^a-z0-9\\._-]/i;\n URI.punycode_expression = /(xn--)/i;\n // well, 333.444.555.666 matches, but it sure ain't no IPv4 - do we care?\n URI.ip4_expression = /^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/;\n // credits to Rich Brown\n // source: http://forums.intermapper.com/viewtopic.php?p=1096#1096\n // specification: http://www.ietf.org/rfc/rfc4291.txt\n URI.ip6_expression = /^\\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:)))(%.+)?\\s*$/;\n // expression used is \"gruber revised\" (@gruber v2) determined to be the\n // best solution in a regex-golf we did a couple of ages ago at\n // * http://mathiasbynens.be/demo/url-regex\n // * http://rodneyrehm.de/t/url-regex.html\n URI.find_uri_expression = /\\b((?:[a-z][\\w-]+:(?:\\/{1,3}|[a-z0-9%])|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,4}\\/)(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))+(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|[^\\s`!()\\[\\]{};:'\".,<>?\u00AB\u00BB\u201C\u201D\u2018\u2019]))/ig;\n URI.findUri = {\n // valid \"scheme://\" or \"www.\"\n start: /\\b(?:([a-z][a-z0-9.+-]*:\\/\\/)|www\\.)/gi,\n // everything up to the next whitespace\n end: /[\\s\\r\\n]|$/,\n // trim trailing punctuation captured by end RegExp\n trim: /[`!()\\[\\]{};:'\".,<>?\u00AB\u00BB\u201C\u201D\u201E\u2018\u2019]+$/,\n // balanced parens inclusion (), [], {}, <>\n parens: /(\\([^\\)]*\\)|\\[[^\\]]*\\]|\\{[^}]*\\}|<[^>]*>)/g,\n };\n URI.leading_whitespace_expression = /^[\\x00-\\x20\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]+/\n // https://infra.spec.whatwg.org/#ascii-tab-or-newline\n URI.ascii_tab_whitespace = /[\\u0009\\u000A\\u000D]+/g\n // http://www.iana.org/assignments/uri-schemes.html\n // http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports\n URI.defaultPorts = {\n http: '80',\n https: '443',\n ftp: '21',\n gopher: '70',\n ws: '80',\n wss: '443'\n };\n // list of protocols which always require a hostname\n URI.hostProtocols = [\n 'http',\n 'https'\n ];\n\n // allowed hostname characters according to RFC 3986\n // ALPHA DIGIT \"-\" \".\" \"_\" \"~\" \"!\" \"$\" \"&\" \"'\" \"(\" \")\" \"*\" \"+\" \",\" \";\" \"=\" %encoded\n // I've never seen a (non-IDN) hostname other than: ALPHA DIGIT . - _\n URI.invalid_hostname_characters = /[^a-zA-Z0-9\\.\\-:_]/;\n // map DOM Elements to their URI attribute\n URI.domAttributes = {\n 'a': 'href',\n 'blockquote': 'cite',\n 'link': 'href',\n 'base': 'href',\n 'script': 'src',\n 'form': 'action',\n 'img': 'src',\n 'area': 'href',\n 'iframe': 'src',\n 'embed': 'src',\n 'source': 'src',\n 'track': 'src',\n 'input': 'src', // but only if type=\"image\"\n 'audio': 'src',\n 'video': 'src'\n };\n URI.getDomAttribute = function(node) {\n if (!node || !node.nodeName) {\n return undefined;\n }\n\n var nodeName = node.nodeName.toLowerCase();\n // should only expose src for type=\"image\"\n if (nodeName === 'input' && node.type !== 'image') {\n return undefined;\n }\n\n return URI.domAttributes[nodeName];\n };\n\n function escapeForDumbFirefox36(value) {\n // https://github.com/medialize/URI.js/issues/91\n return escape(value);\n }\n\n // encoding / decoding according to RFC3986\n function strictEncodeURIComponent(string) {\n // see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/encodeURIComponent\n return encodeURIComponent(string)\n .replace(/[!'()*]/g, escapeForDumbFirefox36)\n .replace(/\\*/g, '%2A');\n }\n URI.encode = strictEncodeURIComponent;\n URI.decode = decodeURIComponent;\n URI.iso8859 = function() {\n URI.encode = escape;\n URI.decode = unescape;\n };\n URI.unicode = function() {\n URI.encode = strictEncodeURIComponent;\n URI.decode = decodeURIComponent;\n };\n URI.characters = {\n pathname: {\n encode: {\n // RFC3986 2.1: For consistency, URI producers and normalizers should\n // use uppercase hexadecimal digits for all percent-encodings.\n expression: /%(24|26|2B|2C|3B|3D|3A|40)/ig,\n map: {\n // -._~!'()*\n '%24': '$',\n '%26': '&',\n '%2B': '+',\n '%2C': ',',\n '%3B': ';',\n '%3D': '=',\n '%3A': ':',\n '%40': '@'\n }\n },\n decode: {\n expression: /[\\/\\?#]/g,\n map: {\n '/': '%2F',\n '?': '%3F',\n '#': '%23'\n }\n }\n },\n reserved: {\n encode: {\n // RFC3986 2.1: For consistency, URI producers and normalizers should\n // use uppercase hexadecimal digits for all percent-encodings.\n expression: /%(21|23|24|26|27|28|29|2A|2B|2C|2F|3A|3B|3D|3F|40|5B|5D)/ig,\n map: {\n // gen-delims\n '%3A': ':',\n '%2F': '/',\n '%3F': '?',\n '%23': '#',\n '%5B': '[',\n '%5D': ']',\n '%40': '@',\n // sub-delims\n '%21': '!',\n '%24': '$',\n '%26': '&',\n '%27': '\\'',\n '%28': '(',\n '%29': ')',\n '%2A': '*',\n '%2B': '+',\n '%2C': ',',\n '%3B': ';',\n '%3D': '='\n }\n }\n },\n urnpath: {\n // The characters under `encode` are the characters called out by RFC 2141 as being acceptable\n // for usage in a URN. RFC2141 also calls out \"-\", \".\", and \"_\" as acceptable characters, but\n // these aren't encoded by encodeURIComponent, so we don't have to call them out here. Also\n // note that the colon character is not featured in the encoding map; this is because URI.js\n // gives the colons in URNs semantic meaning as the delimiters of path segements, and so it\n // should not appear unencoded in a segment itself.\n // See also the note above about RFC3986 and capitalalized hex digits.\n encode: {\n expression: /%(21|24|27|28|29|2A|2B|2C|3B|3D|40)/ig,\n map: {\n '%21': '!',\n '%24': '$',\n '%27': '\\'',\n '%28': '(',\n '%29': ')',\n '%2A': '*',\n '%2B': '+',\n '%2C': ',',\n '%3B': ';',\n '%3D': '=',\n '%40': '@'\n }\n },\n // These characters are the characters called out by RFC2141 as \"reserved\" characters that\n // should never appear in a URN, plus the colon character (see note above).\n decode: {\n expression: /[\\/\\?#:]/g,\n map: {\n '/': '%2F',\n '?': '%3F',\n '#': '%23',\n ':': '%3A'\n }\n }\n }\n };\n URI.encodeQuery = function(string, escapeQuerySpace) {\n var escaped = URI.encode(string + '');\n if (escapeQuerySpace === undefined) {\n escapeQuerySpace = URI.escapeQuerySpace;\n }\n\n return escapeQuerySpace ? escaped.replace(/%20/g, '+') : escaped;\n };\n URI.decodeQuery = function(string, escapeQuerySpace) {\n string += '';\n if (escapeQuerySpace === undefined) {\n escapeQuerySpace = URI.escapeQuerySpace;\n }\n\n try {\n return URI.decode(escapeQuerySpace ? string.replace(/\\+/g, '%20') : string);\n } catch(e) {\n // we're not going to mess with weird encodings,\n // give up and return the undecoded original string\n // see https://github.com/medialize/URI.js/issues/87\n // see https://github.com/medialize/URI.js/issues/92\n return string;\n }\n };\n // generate encode/decode path functions\n var _parts = {'encode':'encode', 'decode':'decode'};\n var _part;\n var generateAccessor = function(_group, _part) {\n return function(string) {\n try {\n return URI[_part](string + '').replace(URI.characters[_group][_part].expression, function(c) {\n return URI.characters[_group][_part].map[c];\n });\n } catch (e) {\n // we're not going to mess with weird encodings,\n // give up and return the undecoded original string\n // see https://github.com/medialize/URI.js/issues/87\n // see https://github.com/medialize/URI.js/issues/92\n return string;\n }\n };\n };\n\n for (_part in _parts) {\n URI[_part + 'PathSegment'] = generateAccessor('pathname', _parts[_part]);\n URI[_part + 'UrnPathSegment'] = generateAccessor('urnpath', _parts[_part]);\n }\n\n var generateSegmentedPathFunction = function(_sep, _codingFuncName, _innerCodingFuncName) {\n return function(string) {\n // Why pass in names of functions, rather than the function objects themselves? The\n // definitions of some functions (but in particular, URI.decode) will occasionally change due\n // to URI.js having ISO8859 and Unicode modes. Passing in the name and getting it will ensure\n // that the functions we use here are \"fresh\".\n var actualCodingFunc;\n if (!_innerCodingFuncName) {\n actualCodingFunc = URI[_codingFuncName];\n } else {\n actualCodingFunc = function(string) {\n return URI[_codingFuncName](URI[_innerCodingFuncName](string));\n };\n }\n\n var segments = (string + '').split(_sep);\n\n for (var i = 0, length = segments.length; i < length; i++) {\n segments[i] = actualCodingFunc(segments[i]);\n }\n\n return segments.join(_sep);\n };\n };\n\n // This takes place outside the above loop because we don't want, e.g., encodeUrnPath functions.\n URI.decodePath = generateSegmentedPathFunction('/', 'decodePathSegment');\n URI.decodeUrnPath = generateSegmentedPathFunction(':', 'decodeUrnPathSegment');\n URI.recodePath = generateSegmentedPathFunction('/', 'encodePathSegment', 'decode');\n URI.recodeUrnPath = generateSegmentedPathFunction(':', 'encodeUrnPathSegment', 'decode');\n\n URI.encodeReserved = generateAccessor('reserved', 'encode');\n\n URI.parse = function(string, parts) {\n var pos;\n if (!parts) {\n parts = {\n preventInvalidHostname: URI.preventInvalidHostname\n };\n }\n\n string = string.replace(URI.leading_whitespace_expression, '')\n // https://infra.spec.whatwg.org/#ascii-tab-or-newline\n string = string.replace(URI.ascii_tab_whitespace, '')\n\n // [protocol\"://\"[username[\":\"password]\"@\"]hostname[\":\"port]\"/\"?][path][\"?\"querystring][\"#\"fragment]\n\n // extract fragment\n pos = string.indexOf('#');\n if (pos > -1) {\n // escaping?\n parts.fragment = string.substring(pos + 1) || null;\n string = string.substring(0, pos);\n }\n\n // extract query\n pos = string.indexOf('?');\n if (pos > -1) {\n // escaping?\n parts.query = string.substring(pos + 1) || null;\n string = string.substring(0, pos);\n }\n\n // slashes and backslashes have lost all meaning for the web protocols (https, http, wss, ws)\n string = string.replace(/^(https?|ftp|wss?)?:+[/\\\\]*/i, '$1://');\n // slashes and backslashes have lost all meaning for scheme relative URLs\n string = string.replace(/^[/\\\\]{2,}/i, '//');\n\n // extract protocol\n if (string.substring(0, 2) === '//') {\n // relative-scheme\n parts.protocol = null;\n string = string.substring(2);\n // extract \"user:pass@host:port\"\n string = URI.parseAuthority(string, parts);\n } else {\n pos = string.indexOf(':');\n if (pos > -1) {\n parts.protocol = string.substring(0, pos) || null;\n if (parts.protocol && !parts.protocol.match(URI.protocol_expression)) {\n // : may be within the path\n parts.protocol = undefined;\n } else if (string.substring(pos + 1, pos + 3).replace(/\\\\/g, '/') === '//') {\n string = string.substring(pos + 3);\n\n // extract \"user:pass@host:port\"\n string = URI.parseAuthority(string, parts);\n } else {\n string = string.substring(pos + 1);\n parts.urn = true;\n }\n }\n }\n\n // what's left must be the path\n parts.path = string;\n\n // and we're done\n return parts;\n };\n URI.parseHost = function(string, parts) {\n if (!string) {\n string = '';\n }\n\n // Copy chrome, IE, opera backslash-handling behavior.\n // Back slashes before the query string get converted to forward slashes\n // See: https://github.com/joyent/node/blob/386fd24f49b0e9d1a8a076592a404168faeecc34/lib/url.js#L115-L124\n // See: https://code.google.com/p/chromium/issues/detail?id=25916\n // https://github.com/medialize/URI.js/pull/233\n string = string.replace(/\\\\/g, '/');\n\n // extract host:port\n var pos = string.indexOf('/');\n var bracketPos;\n var t;\n\n if (pos === -1) {\n pos = string.length;\n }\n\n if (string.charAt(0) === '[') {\n // IPv6 host - http://tools.ietf.org/html/draft-ietf-6man-text-addr-representation-04#section-6\n // I claim most client software breaks on IPv6 anyways. To simplify things, URI only accepts\n // IPv6+port in the format [2001:db8::1]:80 (for the time being)\n bracketPos = string.indexOf(']');\n parts.hostname = string.substring(1, bracketPos) || null;\n parts.port = string.substring(bracketPos + 2, pos) || null;\n if (parts.port === '/') {\n parts.port = null;\n }\n } else {\n var firstColon = string.indexOf(':');\n var firstSlash = string.indexOf('/');\n var nextColon = string.indexOf(':', firstColon + 1);\n if (nextColon !== -1 && (firstSlash === -1 || nextColon < firstSlash)) {\n // IPv6 host contains multiple colons - but no port\n // this notation is actually not allowed by RFC 3986, but we're a liberal parser\n parts.hostname = string.substring(0, pos) || null;\n parts.port = null;\n } else {\n t = string.substring(0, pos).split(':');\n parts.hostname = t[0] || null;\n parts.port = t[1] || null;\n }\n }\n\n if (parts.hostname && string.substring(pos).charAt(0) !== '/') {\n pos++;\n string = '/' + string;\n }\n\n if (parts.preventInvalidHostname) {\n URI.ensureValidHostname(parts.hostname, parts.protocol);\n }\n\n if (parts.port) {\n URI.ensureValidPort(parts.port);\n }\n\n return string.substring(pos) || '/';\n };\n URI.parseAuthority = function(string, parts) {\n string = URI.parseUserinfo(string, parts);\n return URI.parseHost(string, parts);\n };\n URI.parseUserinfo = function(string, parts) {\n // extract username:password\n var _string = string\n var firstBackSlash = string.indexOf('\\\\');\n if (firstBackSlash !== -1) {\n string = string.replace(/\\\\/g, '/')\n }\n var firstSlash = string.indexOf('/');\n var pos = string.lastIndexOf('@', firstSlash > -1 ? firstSlash : string.length - 1);\n var t;\n\n // authority@ must come before /path or \\path\n if (pos > -1 && (firstSlash === -1 || pos < firstSlash)) {\n t = string.substring(0, pos).split(':');\n parts.username = t[0] ? URI.decode(t[0]) : null;\n t.shift();\n parts.password = t[0] ? URI.decode(t.join(':')) : null;\n string = _string.substring(pos + 1);\n } else {\n parts.username = null;\n parts.password = null;\n }\n\n return string;\n };\n URI.parseQuery = function(string, escapeQuerySpace) {\n if (!string) {\n return {};\n }\n\n // throw out the funky business - \"?\"[name\"=\"value\"&\"]+\n string = string.replace(/&+/g, '&').replace(/^\\?*&*|&+$/g, '');\n\n if (!string) {\n return {};\n }\n\n var items = {};\n var splits = string.split('&');\n var length = splits.length;\n var v, name, value;\n\n for (var i = 0; i < length; i++) {\n v = splits[i].split('=');\n name = URI.decodeQuery(v.shift(), escapeQuerySpace);\n // no \"=\" is null according to http://dvcs.w3.org/hg/url/raw-file/tip/Overview.html#collect-url-parameters\n value = v.length ? URI.decodeQuery(v.join('='), escapeQuerySpace) : null;\n\n if (name === '__proto__') {\n // ignore attempt at exploiting JavaScript internals\n continue;\n } else if (hasOwn.call(items, name)) {\n if (typeof items[name] === 'string' || items[name] === null) {\n items[name] = [items[name]];\n }\n\n items[name].push(value);\n } else {\n items[name] = value;\n }\n }\n\n return items;\n };\n\n URI.build = function(parts) {\n var t = '';\n var requireAbsolutePath = false\n\n if (parts.protocol) {\n t += parts.protocol + ':';\n }\n\n if (!parts.urn && (t || parts.hostname)) {\n t += '//';\n requireAbsolutePath = true\n }\n\n t += (URI.buildAuthority(parts) || '');\n\n if (typeof parts.path === 'string') {\n if (parts.path.charAt(0) !== '/' && requireAbsolutePath) {\n t += '/';\n }\n\n t += parts.path;\n }\n\n if (typeof parts.query === 'string' && parts.query) {\n t += '?' + parts.query;\n }\n\n if (typeof parts.fragment === 'string' && parts.fragment) {\n t += '#' + parts.fragment;\n }\n return t;\n };\n URI.buildHost = function(parts) {\n var t = '';\n\n if (!parts.hostname) {\n return '';\n } else if (URI.ip6_expression.test(parts.hostname)) {\n t += '[' + parts.hostname + ']';\n } else {\n t += parts.hostname;\n }\n\n if (parts.port) {\n t += ':' + parts.port;\n }\n\n return t;\n };\n URI.buildAuthority = function(parts) {\n return URI.buildUserinfo(parts) + URI.buildHost(parts);\n };\n URI.buildUserinfo = function(parts) {\n var t = '';\n\n if (parts.username) {\n t += URI.encode(parts.username);\n }\n\n if (parts.password) {\n t += ':' + URI.encode(parts.password);\n }\n\n if (t) {\n t += '@';\n }\n\n return t;\n };\n URI.buildQuery = function(data, duplicateQueryParameters, escapeQuerySpace) {\n // according to http://tools.ietf.org/html/rfc3986 or http://labs.apache.org/webarch/uri/rfc/rfc3986.html\n // being \u00BB-._~!$&'()*+,;=:@/?\u00AB %HEX and alnum are allowed\n // the RFC explicitly states ?/foo being a valid use case, no mention of parameter syntax!\n // URI.js treats the query string as being application/x-www-form-urlencoded\n // see http://www.w3.org/TR/REC-html40/interact/forms.html#form-content-type\n\n var t = '';\n var unique, key, i, length;\n for (key in data) {\n if (key === '__proto__') {\n // ignore attempt at exploiting JavaScript internals\n continue;\n } else if (hasOwn.call(data, key)) {\n if (isArray(data[key])) {\n unique = {};\n for (i = 0, length = data[key].length; i < length; i++) {\n if (data[key][i] !== undefined && unique[data[key][i] + ''] === undefined) {\n t += '&' + URI.buildQueryParameter(key, data[key][i], escapeQuerySpace);\n if (duplicateQueryParameters !== true) {\n unique[data[key][i] + ''] = true;\n }\n }\n }\n } else if (data[key] !== undefined) {\n t += '&' + URI.buildQueryParameter(key, data[key], escapeQuerySpace);\n }\n }\n }\n\n return t.substring(1);\n };\n URI.buildQueryParameter = function(name, value, escapeQuerySpace) {\n // http://www.w3.org/TR/REC-html40/interact/forms.html#form-content-type -- application/x-www-form-urlencoded\n // don't append \"=\" for null values, according to http://dvcs.w3.org/hg/url/raw-file/tip/Overview.html#url-parameter-serialization\n return URI.encodeQuery(name, escapeQuerySpace) + (value !== null ? '=' + URI.encodeQuery(value, escapeQuerySpace) : '');\n };\n\n URI.addQuery = function(data, name, value) {\n if (typeof name === 'object') {\n for (var key in name) {\n if (hasOwn.call(name, key)) {\n URI.addQuery(data, key, name[key]);\n }\n }\n } else if (typeof name === 'string') {\n if (data[name] === undefined) {\n data[name] = value;\n return;\n } else if (typeof data[name] === 'string') {\n data[name] = [data[name]];\n }\n\n if (!isArray(value)) {\n value = [value];\n }\n\n data[name] = (data[name] || []).concat(value);\n } else {\n throw new TypeError('URI.addQuery() accepts an object, string as the name parameter');\n }\n };\n\n URI.setQuery = function(data, name, value) {\n if (typeof name === 'object') {\n for (var key in name) {\n if (hasOwn.call(name, key)) {\n URI.setQuery(data, key, name[key]);\n }\n }\n } else if (typeof name === 'string') {\n data[name] = value === undefined ? null : value;\n } else {\n throw new TypeError('URI.setQuery() accepts an object, string as the name parameter');\n }\n };\n\n URI.removeQuery = function(data, name, value) {\n var i, length, key;\n\n if (isArray(name)) {\n for (i = 0, length = name.length; i < length; i++) {\n data[name[i]] = undefined;\n }\n } else if (getType(name) === 'RegExp') {\n for (key in data) {\n if (name.test(key)) {\n data[key] = undefined;\n }\n }\n } else if (typeof name === 'object') {\n for (key in name) {\n if (hasOwn.call(name, key)) {\n URI.removeQuery(data, key, name[key]);\n }\n }\n } else if (typeof name === 'string') {\n if (value !== undefined) {\n if (getType(value) === 'RegExp') {\n if (!isArray(data[name]) && value.test(data[name])) {\n data[name] = undefined;\n } else {\n data[name] = filterArrayValues(data[name], value);\n }\n } else if (data[name] === String(value) && (!isArray(value) || value.length === 1)) {\n data[name] = undefined;\n } else if (isArray(data[name])) {\n data[name] = filterArrayValues(data[name], value);\n }\n } else {\n data[name] = undefined;\n }\n } else {\n throw new TypeError('URI.removeQuery() accepts an object, string, RegExp as the first parameter');\n }\n };\n URI.hasQuery = function(data, name, value, withinArray) {\n switch (getType(name)) {\n case 'String':\n // Nothing to do here\n break;\n\n case 'RegExp':\n for (var key in data) {\n if (hasOwn.call(data, key)) {\n if (name.test(key) && (value === undefined || URI.hasQuery(data, key, value))) {\n return true;\n }\n }\n }\n\n return false;\n\n case 'Object':\n for (var _key in name) {\n if (hasOwn.call(name, _key)) {\n if (!URI.hasQuery(data, _key, name[_key])) {\n return false;\n }\n }\n }\n\n return true;\n\n default:\n throw new TypeError('URI.hasQuery() accepts a string, regular expression or object as the name parameter');\n }\n\n switch (getType(value)) {\n case 'Undefined':\n // true if exists (but may be empty)\n return name in data; // data[name] !== undefined;\n\n case 'Boolean':\n // true if exists and non-empty\n var _booly = Boolean(isArray(data[name]) ? data[name].length : data[name]);\n return value === _booly;\n\n case 'Function':\n // allow complex comparison\n return !!value(data[name], name, data);\n\n case 'Array':\n if (!isArray(data[name])) {\n return false;\n }\n\n var op = withinArray ? arrayContains : arraysEqual;\n return op(data[name], value);\n\n case 'RegExp':\n if (!isArray(data[name])) {\n return Boolean(data[name] && data[name].match(value));\n }\n\n if (!withinArray) {\n return false;\n }\n\n return arrayContains(data[name], value);\n\n case 'Number':\n value = String(value);\n /* falls through */\n case 'String':\n if (!isArray(data[name])) {\n return data[name] === value;\n }\n\n if (!withinArray) {\n return false;\n }\n\n return arrayContains(data[name], value);\n\n default:\n throw new TypeError('URI.hasQuery() accepts undefined, boolean, string, number, RegExp, Function as the value parameter');\n }\n };\n\n\n URI.joinPaths = function() {\n var input = [];\n var segments = [];\n var nonEmptySegments = 0;\n\n for (var i = 0; i < arguments.length; i++) {\n var url = new URI(arguments[i]);\n input.push(url);\n var _segments = url.segment();\n for (var s = 0; s < _segments.length; s++) {\n if (typeof _segments[s] === 'string') {\n segments.push(_segments[s]);\n }\n\n if (_segments[s]) {\n nonEmptySegments++;\n }\n }\n }\n\n if (!segments.length || !nonEmptySegments) {\n return new URI('');\n }\n\n var uri = new URI('').segment(segments);\n\n if (input[0].path() === '' || input[0].path().slice(0, 1) === '/') {\n uri.path('/' + uri.path());\n }\n\n return uri.normalize();\n };\n\n URI.commonPath = function(one, two) {\n var length = Math.min(one.length, two.length);\n var pos;\n\n // find first non-matching character\n for (pos = 0; pos < length; pos++) {\n if (one.charAt(pos) !== two.charAt(pos)) {\n pos--;\n break;\n }\n }\n\n if (pos < 1) {\n return one.charAt(0) === two.charAt(0) && one.charAt(0) === '/' ? '/' : '';\n }\n\n // revert to last /\n if (one.charAt(pos) !== '/' || two.charAt(pos) !== '/') {\n pos = one.substring(0, pos).lastIndexOf('/');\n }\n\n return one.substring(0, pos + 1);\n };\n\n URI.withinString = function(string, callback, options) {\n options || (options = {});\n var _start = options.start || URI.findUri.start;\n var _end = options.end || URI.findUri.end;\n var _trim = options.trim || URI.findUri.trim;\n var _parens = options.parens || URI.findUri.parens;\n var _attributeOpen = /[a-z0-9-]=[\"']?$/i;\n\n _start.lastIndex = 0;\n while (true) {\n var match = _start.exec(string);\n if (!match) {\n break;\n }\n\n var start = match.index;\n if (options.ignoreHtml) {\n // attribut(e=[\"']?$)\n var attributeOpen = string.slice(Math.max(start - 3, 0), start);\n if (attributeOpen && _attributeOpen.test(attributeOpen)) {\n continue;\n }\n }\n\n var end = start + string.slice(start).search(_end);\n var slice = string.slice(start, end);\n // make sure we include well balanced parens\n var parensEnd = -1;\n while (true) {\n var parensMatch = _parens.exec(slice);\n if (!parensMatch) {\n break;\n }\n\n var parensMatchEnd = parensMatch.index + parensMatch[0].length;\n parensEnd = Math.max(parensEnd, parensMatchEnd);\n }\n\n if (parensEnd > -1) {\n slice = slice.slice(0, parensEnd) + slice.slice(parensEnd).replace(_trim, '');\n } else {\n slice = slice.replace(_trim, '');\n }\n\n if (slice.length <= match[0].length) {\n // the extract only contains the starting marker of a URI,\n // e.g. \"www\" or \"http://\"\n continue;\n }\n\n if (options.ignore && options.ignore.test(slice)) {\n continue;\n }\n\n end = start + slice.length;\n var result = callback(slice, start, end, string);\n if (result === undefined) {\n _start.lastIndex = end;\n continue;\n }\n\n result = String(result);\n string = string.slice(0, start) + result + string.slice(end);\n _start.lastIndex = start + result.length;\n }\n\n _start.lastIndex = 0;\n return string;\n };\n\n URI.ensureValidHostname = function(v, protocol) {\n // Theoretically URIs allow percent-encoding in Hostnames (according to RFC 3986)\n // they are not part of DNS and therefore ignored by URI.js\n\n var hasHostname = !!v; // not null and not an empty string\n var hasProtocol = !!protocol;\n var rejectEmptyHostname = false;\n\n if (hasProtocol) {\n rejectEmptyHostname = arrayContains(URI.hostProtocols, protocol);\n }\n\n if (rejectEmptyHostname && !hasHostname) {\n throw new TypeError('Hostname cannot be empty, if protocol is ' + protocol);\n } else if (v && v.match(URI.invalid_hostname_characters)) {\n // test punycode\n if (!punycode) {\n throw new TypeError('Hostname \"' + v + '\" contains characters other than [A-Z0-9.-:_] and Punycode.js is not available');\n }\n if (punycode.toASCII(v).match(URI.invalid_hostname_characters)) {\n throw new TypeError('Hostname \"' + v + '\" contains characters other than [A-Z0-9.-:_]');\n }\n }\n };\n\n URI.ensureValidPort = function (v) {\n if (!v) {\n return;\n }\n\n var port = Number(v);\n if (isInteger(port) && (port > 0) && (port < 65536)) {\n return;\n }\n\n throw new TypeError('Port \"' + v + '\" is not a valid port');\n };\n\n // noConflict\n URI.noConflict = function(removeAll) {\n if (removeAll) {\n var unconflicted = {\n URI: this.noConflict()\n };\n\n if (root.URITemplate && typeof root.URITemplate.noConflict === 'function') {\n unconflicted.URITemplate = root.URITemplate.noConflict();\n }\n\n if (root.IPv6 && typeof root.IPv6.noConflict === 'function') {\n unconflicted.IPv6 = root.IPv6.noConflict();\n }\n\n if (root.SecondLevelDomains && typeof root.SecondLevelDomains.noConflict === 'function') {\n unconflicted.SecondLevelDomains = root.SecondLevelDomains.noConflict();\n }\n\n return unconflicted;\n } else if (root.URI === this) {\n root.URI = _URI;\n }\n\n return this;\n };\n\n p.build = function(deferBuild) {\n if (deferBuild === true) {\n this._deferred_build = true;\n } else if (deferBuild === undefined || this._deferred_build) {\n this._string = URI.build(this._parts);\n this._deferred_build = false;\n }\n\n return this;\n };\n\n p.clone = function() {\n return new URI(this);\n };\n\n p.valueOf = p.toString = function() {\n return this.build(false)._string;\n };\n\n\n function generateSimpleAccessor(_part){\n return function(v, build) {\n if (v === undefined) {\n return this._parts[_part] || '';\n } else {\n this._parts[_part] = v || null;\n this.build(!build);\n return this;\n }\n };\n }\n\n function generatePrefixAccessor(_part, _key){\n return function(v, build) {\n if (v === undefined) {\n return this._parts[_part] || '';\n } else {\n if (v !== null) {\n v = v + '';\n if (v.charAt(0) === _key) {\n v = v.substring(1);\n }\n }\n\n this._parts[_part] = v;\n this.build(!build);\n return this;\n }\n };\n }\n\n p.protocol = generateSimpleAccessor('protocol');\n p.username = generateSimpleAccessor('username');\n p.password = generateSimpleAccessor('password');\n p.hostname = generateSimpleAccessor('hostname');\n p.port = generateSimpleAccessor('port');\n p.query = generatePrefixAccessor('query', '?');\n p.fragment = generatePrefixAccessor('fragment', '#');\n\n p.search = function(v, build) {\n var t = this.query(v, build);\n return typeof t === 'string' && t.length ? ('?' + t) : t;\n };\n p.hash = function(v, build) {\n var t = this.fragment(v, build);\n return typeof t === 'string' && t.length ? ('#' + t) : t;\n };\n\n p.pathname = function(v, build) {\n if (v === undefined || v === true) {\n var res = this._parts.path || (this._parts.hostname ? '/' : '');\n return v ? (this._parts.urn ? URI.decodeUrnPath : URI.decodePath)(res) : res;\n } else {\n if (this._parts.urn) {\n this._parts.path = v ? URI.recodeUrnPath(v) : '';\n } else {\n this._parts.path = v ? URI.recodePath(v) : '/';\n }\n this.build(!build);\n return this;\n }\n };\n p.path = p.pathname;\n p.href = function(href, build) {\n var key;\n\n if (href === undefined) {\n return this.toString();\n }\n\n this._string = '';\n this._parts = URI._parts();\n\n var _URI = href instanceof URI;\n var _object = typeof href === 'object' && (href.hostname || href.path || href.pathname);\n if (href.nodeName) {\n var attribute = URI.getDomAttribute(href);\n href = href[attribute] || '';\n _object = false;\n }\n\n // window.location is reported to be an object, but it's not the sort\n // of object we're looking for:\n // * location.protocol ends with a colon\n // * location.query != object.search\n // * location.hash != object.fragment\n // simply serializing the unknown object should do the trick\n // (for location, not for everything...)\n if (!_URI && _object && href.pathname !== undefined) {\n href = href.toString();\n }\n\n if (typeof href === 'string' || href instanceof String) {\n this._parts = URI.parse(String(href), this._parts);\n } else if (_URI || _object) {\n var src = _URI ? href._parts : href;\n for (key in src) {\n if (key === 'query') { continue; }\n if (hasOwn.call(this._parts, key)) {\n this._parts[key] = src[key];\n }\n }\n if (src.query) {\n this.query(src.query, false);\n }\n } else {\n throw new TypeError('invalid input');\n }\n\n this.build(!build);\n return this;\n };\n\n // identification accessors\n p.is = function(what) {\n var ip = false;\n var ip4 = false;\n var ip6 = false;\n var name = false;\n var sld = false;\n var idn = false;\n var punycode = false;\n var relative = !this._parts.urn;\n\n if (this._parts.hostname) {\n relative = false;\n ip4 = URI.ip4_expression.test(this._parts.hostname);\n ip6 = URI.ip6_expression.test(this._parts.hostname);\n ip = ip4 || ip6;\n name = !ip;\n sld = name && SLD && SLD.has(this._parts.hostname);\n idn = name && URI.idn_expression.test(this._parts.hostname);\n punycode = name && URI.punycode_expression.test(this._parts.hostname);\n }\n\n switch (what.toLowerCase()) {\n case 'relative':\n return relative;\n\n case 'absolute':\n return !relative;\n\n // hostname identification\n case 'domain':\n case 'name':\n return name;\n\n case 'sld':\n return sld;\n\n case 'ip':\n return ip;\n\n case 'ip4':\n case 'ipv4':\n case 'inet4':\n return ip4;\n\n case 'ip6':\n case 'ipv6':\n case 'inet6':\n return ip6;\n\n case 'idn':\n return idn;\n\n case 'url':\n return !this._parts.urn;\n\n case 'urn':\n return !!this._parts.urn;\n\n case 'punycode':\n return punycode;\n }\n\n return null;\n };\n\n // component specific input validation\n var _protocol = p.protocol;\n var _port = p.port;\n var _hostname = p.hostname;\n\n p.protocol = function(v, build) {\n if (v) {\n // accept trailing ://\n v = v.replace(/:(\\/\\/)?$/, '');\n\n if (!v.match(URI.protocol_expression)) {\n throw new TypeError('Protocol \"' + v + '\" contains characters other than [A-Z0-9.+-] or doesn\\'t start with [A-Z]');\n }\n }\n\n return _protocol.call(this, v, build);\n };\n p.scheme = p.protocol;\n p.port = function(v, build) {\n if (this._parts.urn) {\n return v === undefined ? '' : this;\n }\n\n if (v !== undefined) {\n if (v === 0) {\n v = null;\n }\n\n if (v) {\n v += '';\n if (v.charAt(0) === ':') {\n v = v.substring(1);\n }\n\n URI.ensureValidPort(v);\n }\n }\n return _port.call(this, v, build);\n };\n p.hostname = function(v, build) {\n if (this._parts.urn) {\n return v === undefined ? '' : this;\n }\n\n if (v !== undefined) {\n var x = { preventInvalidHostname: this._parts.preventInvalidHostname };\n var res = URI.parseHost(v, x);\n if (res !== '/') {\n throw new TypeError('Hostname \"' + v + '\" contains characters other than [A-Z0-9.-]');\n }\n\n v = x.hostname;\n if (this._parts.preventInvalidHostname) {\n URI.ensureValidHostname(v, this._parts.protocol);\n }\n }\n\n return _hostname.call(this, v, build);\n };\n\n // compound accessors\n p.origin = function(v, build) {\n if (this._parts.urn) {\n return v === undefined ? '' : this;\n }\n\n if (v === undefined) {\n var protocol = this.protocol();\n var authority = this.authority();\n if (!authority) {\n return '';\n }\n\n return (protocol ? protocol + '://' : '') + this.authority();\n } else {\n var origin = URI(v);\n this\n .protocol(origin.protocol())\n .authority(origin.authority())\n .build(!build);\n return this;\n }\n };\n p.host = function(v, build) {\n if (this._parts.urn) {\n return v === undefined ? '' : this;\n }\n\n if (v === undefined) {\n return this._parts.hostname ? URI.buildHost(this._parts) : '';\n } else {\n var res = URI.parseHost(v, this._parts);\n if (res !== '/') {\n throw new TypeError('Hostname \"' + v + '\" contains characters other than [A-Z0-9.-]');\n }\n\n this.build(!build);\n return this;\n }\n };\n p.authority = function(v, build) {\n if (this._parts.urn) {\n return v === undefined ? '' : this;\n }\n\n if (v === undefined) {\n return this._parts.hostname ? URI.buildAuthority(this._parts) : '';\n } else {\n var res = URI.parseAuthority(v, this._parts);\n if (res !== '/') {\n throw new TypeError('Hostname \"' + v + '\" contains characters other than [A-Z0-9.-]');\n }\n\n this.build(!build);\n return this;\n }\n };\n p.userinfo = function(v, build) {\n if (this._parts.urn) {\n return v === undefined ? '' : this;\n }\n\n if (v === undefined) {\n var t = URI.buildUserinfo(this._parts);\n return t ? t.substring(0, t.length -1) : t;\n } else {\n if (v[v.length-1] !== '@') {\n v += '@';\n }\n\n URI.parseUserinfo(v, this._parts);\n this.build(!build);\n return this;\n }\n };\n p.resource = function(v, build) {\n var parts;\n\n if (v === undefined) {\n return this.path() + this.search() + this.hash();\n }\n\n parts = URI.parse(v);\n this._parts.path = parts.path;\n this._parts.query = parts.query;\n this._parts.fragment = parts.fragment;\n this.build(!build);\n return this;\n };\n\n // fraction accessors\n p.subdomain = function(v, build) {\n if (this._parts.urn) {\n return v === undefined ? '' : this;\n }\n\n // convenience, return \"www\" from \"www.example.org\"\n if (v === undefined) {\n if (!this._parts.hostname || this.is('IP')) {\n return '';\n }\n\n // grab domain and add another segment\n var end = this._parts.hostname.length - this.domain().length - 1;\n return this._parts.hostname.substring(0, end) || '';\n } else {\n var e = this._parts.hostname.length - this.domain().length;\n var sub = this._parts.hostname.substring(0, e);\n var replace = new RegExp('^' + escapeRegEx(sub));\n\n if (v && v.charAt(v.length - 1) !== '.') {\n v += '.';\n }\n\n if (v.indexOf(':') !== -1) {\n throw new TypeError('Domains cannot contain colons');\n }\n\n if (v) {\n URI.ensureValidHostname(v, this._parts.protocol);\n }\n\n this._parts.hostname = this._parts.hostname.replace(replace, v);\n this.build(!build);\n return this;\n }\n };\n p.domain = function(v, build) {\n if (this._parts.urn) {\n return v === undefined ? '' : this;\n }\n\n if (typeof v === 'boolean') {\n build = v;\n v = undefined;\n }\n\n // convenience, return \"example.org\" from \"www.example.org\"\n if (v === undefined) {\n if (!this._parts.hostname || this.is('IP')) {\n return '';\n }\n\n // if hostname consists of 1 or 2 segments, it must be the domain\n var t = this._parts.hostname.match(/\\./g);\n if (t && t.length < 2) {\n return this._parts.hostname;\n }\n\n // grab tld and add another segment\n var end = this._parts.hostname.length - this.tld(build).length - 1;\n end = this._parts.hostname.lastIndexOf('.', end -1) + 1;\n return this._parts.hostname.substring(end) || '';\n } else {\n if (!v) {\n throw new TypeError('cannot set domain empty');\n }\n\n if (v.indexOf(':') !== -1) {\n throw new TypeError('Domains cannot contain colons');\n }\n\n URI.ensureValidHostname(v, this._parts.protocol);\n\n if (!this._parts.hostname || this.is('IP')) {\n this._parts.hostname = v;\n } else {\n var replace = new RegExp(escapeRegEx(this.domain()) + '$');\n this._parts.hostname = this._parts.hostname.replace(replace, v);\n }\n\n this.build(!build);\n return this;\n }\n };\n p.tld = function(v, build) {\n if (this._parts.urn) {\n return v === undefined ? '' : this;\n }\n\n if (typeof v === 'boolean') {\n build = v;\n v = undefined;\n }\n\n // return \"org\" from \"www.example.org\"\n if (v === undefined) {\n if (!this._parts.hostname || this.is('IP')) {\n return '';\n }\n\n var pos = this._parts.hostname.lastIndexOf('.');\n var tld = this._parts.hostname.substring(pos + 1);\n\n if (build !== true && SLD && SLD.list[tld.toLowerCase()]) {\n return SLD.get(this._parts.hostname) || tld;\n }\n\n return tld;\n } else {\n var replace;\n\n if (!v) {\n throw new TypeError('cannot set TLD empty');\n } else if (v.match(/[^a-zA-Z0-9-]/)) {\n if (SLD && SLD.is(v)) {\n replace = new RegExp(escapeRegEx(this.tld()) + '$');\n this._parts.hostname = this._parts.hostname.replace(replace, v);\n } else {\n throw new TypeError('TLD \"' + v + '\" contains characters other than [A-Z0-9]');\n }\n } else if (!this._parts.hostname || this.is('IP')) {\n throw new ReferenceError('cannot set TLD on non-domain host');\n } else {\n replace = new RegExp(escapeRegEx(this.tld()) + '$');\n this._parts.hostname = this._parts.hostname.replace(replace, v);\n }\n\n this.build(!build);\n return this;\n }\n };\n p.directory = function(v, build) {\n if (this._parts.urn) {\n return v === undefined ? '' : this;\n }\n\n if (v === undefined || v === true) {\n if (!this._parts.path && !this._parts.hostname) {\n return '';\n }\n\n if (this._parts.path === '/') {\n return '/';\n }\n\n var end = this._parts.path.length - this.filename().length - 1;\n var res = this._parts.path.substring(0, end) || (this._parts.hostname ? '/' : '');\n\n return v ? URI.decodePath(res) : res;\n\n } else {\n var e = this._parts.path.length - this.filename().length;\n var directory = this._parts.path.substring(0, e);\n var replace = new RegExp('^' + escapeRegEx(directory));\n\n // fully qualifier directories begin with a slash\n if (!this.is('relative')) {\n if (!v) {\n v = '/';\n }\n\n if (v.charAt(0) !== '/') {\n v = '/' + v;\n }\n }\n\n // directories always end with a slash\n if (v && v.charAt(v.length - 1) !== '/') {\n v += '/';\n }\n\n v = URI.recodePath(v);\n this._parts.path = this._parts.path.replace(replace, v);\n this.build(!build);\n return this;\n }\n };\n p.filename = function(v, build) {\n if (this._parts.urn) {\n return v === undefined ? '' : this;\n }\n\n if (typeof v !== 'string') {\n if (!this._parts.path || this._parts.path === '/') {\n return '';\n }\n\n var pos = this._parts.path.lastIndexOf('/');\n var res = this._parts.path.substring(pos+1);\n\n return v ? URI.decodePathSegment(res) : res;\n } else {\n var mutatedDirectory = false;\n\n if (v.charAt(0) === '/') {\n v = v.substring(1);\n }\n\n if (v.match(/\\.?\\//)) {\n mutatedDirectory = true;\n }\n\n var replace = new RegExp(escapeRegEx(this.filename()) + '$');\n v = URI.recodePath(v);\n this._parts.path = this._parts.path.replace(replace, v);\n\n if (mutatedDirectory) {\n this.normalizePath(build);\n } else {\n this.build(!build);\n }\n\n return this;\n }\n };\n p.suffix = function(v, build) {\n if (this._parts.urn) {\n return v === undefined ? '' : this;\n }\n\n if (v === undefined || v === true) {\n if (!this._parts.path || this._parts.path === '/') {\n return '';\n }\n\n var filename = this.filename();\n var pos = filename.lastIndexOf('.');\n var s, res;\n\n if (pos === -1) {\n return '';\n }\n\n // suffix may only contain alnum characters (yup, I made this up.)\n s = filename.substring(pos+1);\n res = (/^[a-z0-9%]+$/i).test(s) ? s : '';\n return v ? URI.decodePathSegment(res) : res;\n } else {\n if (v.charAt(0) === '.') {\n v = v.substring(1);\n }\n\n var suffix = this.suffix();\n var replace;\n\n if (!suffix) {\n if (!v) {\n return this;\n }\n\n this._parts.path += '.' + URI.recodePath(v);\n } else if (!v) {\n replace = new RegExp(escapeRegEx('.' + suffix) + '$');\n } else {\n replace = new RegExp(escapeRegEx(suffix) + '$');\n }\n\n if (replace) {\n v = URI.recodePath(v);\n this._parts.path = this._parts.path.replace(replace, v);\n }\n\n this.build(!build);\n return this;\n }\n };\n p.segment = function(segment, v, build) {\n var separator = this._parts.urn ? ':' : '/';\n var path = this.path();\n var absolute = path.substring(0, 1) === '/';\n var segments = path.split(separator);\n\n if (segment !== undefined && typeof segment !== 'number') {\n build = v;\n v = segment;\n segment = undefined;\n }\n\n if (segment !== undefined && typeof segment !== 'number') {\n throw new Error('Bad segment \"' + segment + '\", must be 0-based integer');\n }\n\n if (absolute) {\n segments.shift();\n }\n\n if (segment < 0) {\n // allow negative indexes to address from the end\n segment = Math.max(segments.length + segment, 0);\n }\n\n if (v === undefined) {\n /*jshint laxbreak: true */\n return segment === undefined\n ? segments\n : segments[segment];\n /*jshint laxbreak: false */\n } else if (segment === null || segments[segment] === undefined) {\n if (isArray(v)) {\n segments = [];\n // collapse empty elements within array\n for (var i=0, l=v.length; i < l; i++) {\n if (!v[i].length && (!segments.length || !segments[segments.length -1].length)) {\n continue;\n }\n\n if (segments.length && !segments[segments.length -1].length) {\n segments.pop();\n }\n\n segments.push(trimSlashes(v[i]));\n }\n } else if (v || typeof v === 'string') {\n v = trimSlashes(v);\n if (segments[segments.length -1] === '') {\n // empty trailing elements have to be overwritten\n // to prevent results such as /foo//bar\n segments[segments.length -1] = v;\n } else {\n segments.push(v);\n }\n }\n } else {\n if (v) {\n segments[segment] = trimSlashes(v);\n } else {\n segments.splice(segment, 1);\n }\n }\n\n if (absolute) {\n segments.unshift('');\n }\n\n return this.path(segments.join(separator), build);\n };\n p.segmentCoded = function(segment, v, build) {\n var segments, i, l;\n\n if (typeof segment !== 'number') {\n build = v;\n v = segment;\n segment = undefined;\n }\n\n if (v === undefined) {\n segments = this.segment(segment, v, build);\n if (!isArray(segments)) {\n segments = segments !== undefined ? URI.decode(segments) : undefined;\n } else {\n for (i = 0, l = segments.length; i < l; i++) {\n segments[i] = URI.decode(segments[i]);\n }\n }\n\n return segments;\n }\n\n if (!isArray(v)) {\n v = (typeof v === 'string' || v instanceof String) ? URI.encode(v) : v;\n } else {\n for (i = 0, l = v.length; i < l; i++) {\n v[i] = URI.encode(v[i]);\n }\n }\n\n return this.segment(segment, v, build);\n };\n\n // mutating query string\n var q = p.query;\n p.query = function(v, build) {\n if (v === true) {\n return URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);\n } else if (typeof v === 'function') {\n var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);\n var result = v.call(this, data);\n this._parts.query = URI.buildQuery(result || data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);\n this.build(!build);\n return this;\n } else if (v !== undefined && typeof v !== 'string') {\n this._parts.query = URI.buildQuery(v, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);\n this.build(!build);\n return this;\n } else {\n return q.call(this, v, build);\n }\n };\n p.setQuery = function(name, value, build) {\n var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);\n\n if (typeof name === 'string' || name instanceof String) {\n data[name] = value !== undefined ? value : null;\n } else if (typeof name === 'object') {\n for (var key in name) {\n if (hasOwn.call(name, key)) {\n data[key] = name[key];\n }\n }\n } else {\n throw new TypeError('URI.addQuery() accepts an object, string as the name parameter');\n }\n\n this._parts.query = URI.buildQuery(data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);\n if (typeof name !== 'string') {\n build = value;\n }\n\n this.build(!build);\n return this;\n };\n p.addQuery = function(name, value, build) {\n var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);\n URI.addQuery(data, name, value === undefined ? null : value);\n this._parts.query = URI.buildQuery(data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);\n if (typeof name !== 'string') {\n build = value;\n }\n\n this.build(!build);\n return this;\n };\n p.removeQuery = function(name, value, build) {\n var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);\n URI.removeQuery(data, name, value);\n this._parts.query = URI.buildQuery(data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);\n if (typeof name !== 'string') {\n build = value;\n }\n\n this.build(!build);\n return this;\n };\n p.hasQuery = function(name, value, withinArray) {\n var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);\n return URI.hasQuery(data, name, value, withinArray);\n };\n p.setSearch = p.setQuery;\n p.addSearch = p.addQuery;\n p.removeSearch = p.removeQuery;\n p.hasSearch = p.hasQuery;\n\n // sanitizing URLs\n p.normalize = function() {\n if (this._parts.urn) {\n return this\n .normalizeProtocol(false)\n .normalizePath(false)\n .normalizeQuery(false)\n .normalizeFragment(false)\n .build();\n }\n\n return this\n .normalizeProtocol(false)\n .normalizeHostname(false)\n .normalizePort(false)\n .normalizePath(false)\n .normalizeQuery(false)\n .normalizeFragment(false)\n .build();\n };\n p.normalizeProtocol = function(build) {\n if (typeof this._parts.protocol === 'string') {\n this._parts.protocol = this._parts.protocol.toLowerCase();\n this.build(!build);\n }\n\n return this;\n };\n p.normalizeHostname = function(build) {\n if (this._parts.hostname) {\n if (this.is('IDN') && punycode) {\n this._parts.hostname = punycode.toASCII(this._parts.hostname);\n } else if (this.is('IPv6') && IPv6) {\n this._parts.hostname = IPv6.best(this._parts.hostname);\n }\n\n this._parts.hostname = this._parts.hostname.toLowerCase();\n this.build(!build);\n }\n\n return this;\n };\n p.normalizePort = function(build) {\n // remove port of it's the protocol's default\n if (typeof this._parts.protocol === 'string' && this._parts.port === URI.defaultPorts[this._parts.protocol]) {\n this._parts.port = null;\n this.build(!build);\n }\n\n return this;\n };\n p.normalizePath = function(build) {\n var _path = this._parts.path;\n if (!_path) {\n return this;\n }\n\n if (this._parts.urn) {\n this._parts.path = URI.recodeUrnPath(this._parts.path);\n this.build(!build);\n return this;\n }\n\n if (this._parts.path === '/') {\n return this;\n }\n\n _path = URI.recodePath(_path);\n\n var _was_relative;\n var _leadingParents = '';\n var _parent, _pos;\n\n // handle relative paths\n if (_path.charAt(0) !== '/') {\n _was_relative = true;\n _path = '/' + _path;\n }\n\n // handle relative files (as opposed to directories)\n if (_path.slice(-3) === '/..' || _path.slice(-2) === '/.') {\n _path += '/';\n }\n\n // resolve simples\n _path = _path\n .replace(/(\\/(\\.\\/)+)|(\\/\\.$)/g, '/')\n .replace(/\\/{2,}/g, '/');\n\n // remember leading parents\n if (_was_relative) {\n _leadingParents = _path.substring(1).match(/^(\\.\\.\\/)+/) || '';\n if (_leadingParents) {\n _leadingParents = _leadingParents[0];\n }\n }\n\n // resolve parents\n while (true) {\n _parent = _path.search(/\\/\\.\\.(\\/|$)/);\n if (_parent === -1) {\n // no more ../ to resolve\n break;\n } else if (_parent === 0) {\n // top level cannot be relative, skip it\n _path = _path.substring(3);\n continue;\n }\n\n _pos = _path.substring(0, _parent).lastIndexOf('/');\n if (_pos === -1) {\n _pos = _parent;\n }\n _path = _path.substring(0, _pos) + _path.substring(_parent + 3);\n }\n\n // revert to relative\n if (_was_relative && this.is('relative')) {\n _path = _leadingParents + _path.substring(1);\n }\n\n this._parts.path = _path;\n this.build(!build);\n return this;\n };\n p.normalizePathname = p.normalizePath;\n p.normalizeQuery = function(build) {\n if (typeof this._parts.query === 'string') {\n if (!this._parts.query.length) {\n this._parts.query = null;\n } else {\n this.query(URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace));\n }\n\n this.build(!build);\n }\n\n return this;\n };\n p.normalizeFragment = function(build) {\n if (!this._parts.fragment) {\n this._parts.fragment = null;\n this.build(!build);\n }\n\n return this;\n };\n p.normalizeSearch = p.normalizeQuery;\n p.normalizeHash = p.normalizeFragment;\n\n p.iso8859 = function() {\n // expect unicode input, iso8859 output\n var e = URI.encode;\n var d = URI.decode;\n\n URI.encode = escape;\n URI.decode = decodeURIComponent;\n try {\n this.normalize();\n } finally {\n URI.encode = e;\n URI.decode = d;\n }\n return this;\n };\n\n p.unicode = function() {\n // expect iso8859 input, unicode output\n var e = URI.encode;\n var d = URI.decode;\n\n URI.encode = strictEncodeURIComponent;\n URI.decode = unescape;\n try {\n this.normalize();\n } finally {\n URI.encode = e;\n URI.decode = d;\n }\n return this;\n };\n\n p.readable = function() {\n var uri = this.clone();\n // removing username, password, because they shouldn't be displayed according to RFC 3986\n uri.username('').password('').normalize();\n var t = '';\n if (uri._parts.protocol) {\n t += uri._parts.protocol + '://';\n }\n\n if (uri._parts.hostname) {\n if (uri.is('punycode') && punycode) {\n t += punycode.toUnicode(uri._parts.hostname);\n if (uri._parts.port) {\n t += ':' + uri._parts.port;\n }\n } else {\n t += uri.host();\n }\n }\n\n if (uri._parts.hostname && uri._parts.path && uri._parts.path.charAt(0) !== '/') {\n t += '/';\n }\n\n t += uri.path(true);\n if (uri._parts.query) {\n var q = '';\n for (var i = 0, qp = uri._parts.query.split('&'), l = qp.length; i < l; i++) {\n var kv = (qp[i] || '').split('=');\n q += '&' + URI.decodeQuery(kv[0], this._parts.escapeQuerySpace)\n .replace(/&/g, '%26');\n\n if (kv[1] !== undefined) {\n q += '=' + URI.decodeQuery(kv[1], this._parts.escapeQuerySpace)\n .replace(/&/g, '%26');\n }\n }\n t += '?' + q.substring(1);\n }\n\n t += URI.decodeQuery(uri.hash(), true);\n return t;\n };\n\n // resolving relative and absolute URLs\n p.absoluteTo = function(base) {\n var resolved = this.clone();\n var properties = ['protocol', 'username', 'password', 'hostname', 'port'];\n var basedir, i, p;\n\n if (this._parts.urn) {\n throw new Error('URNs do not have any generally defined hierarchical components');\n }\n\n if (!(base instanceof URI)) {\n base = new URI(base);\n }\n\n if (resolved._parts.protocol) {\n // Directly returns even if this._parts.hostname is empty.\n return resolved;\n } else {\n resolved._parts.protocol = base._parts.protocol;\n }\n\n if (this._parts.hostname) {\n return resolved;\n }\n\n for (i = 0; (p = properties[i]); i++) {\n resolved._parts[p] = base._parts[p];\n }\n\n if (!resolved._parts.path) {\n resolved._parts.path = base._parts.path;\n if (!resolved._parts.query) {\n resolved._parts.query = base._parts.query;\n }\n } else {\n if (resolved._parts.path.substring(-2) === '..') {\n resolved._parts.path += '/';\n }\n\n if (resolved.path().charAt(0) !== '/') {\n basedir = base.directory();\n basedir = basedir ? basedir : base.path().indexOf('/') === 0 ? '/' : '';\n resolved._parts.path = (basedir ? (basedir + '/') : '') + resolved._parts.path;\n resolved.normalizePath();\n }\n }\n\n resolved.build();\n return resolved;\n };\n p.relativeTo = function(base) {\n var relative = this.clone().normalize();\n var relativeParts, baseParts, common, relativePath, basePath;\n\n if (relative._parts.urn) {\n throw new Error('URNs do not have any generally defined hierarchical components');\n }\n\n base = new URI(base).normalize();\n relativeParts = relative._parts;\n baseParts = base._parts;\n relativePath = relative.path();\n basePath = base.path();\n\n if (relativePath.charAt(0) !== '/') {\n throw new Error('URI is already relative');\n }\n\n if (basePath.charAt(0) !== '/') {\n throw new Error('Cannot calculate a URI relative to another relative URI');\n }\n\n if (relativeParts.protocol === baseParts.protocol) {\n relativeParts.protocol = null;\n }\n\n if (relativeParts.username !== baseParts.username || relativeParts.password !== baseParts.password) {\n return relative.build();\n }\n\n if (relativeParts.protocol !== null || relativeParts.username !== null || relativeParts.password !== null) {\n return relative.build();\n }\n\n if (relativeParts.hostname === baseParts.hostname && relativeParts.port === baseParts.port) {\n relativeParts.hostname = null;\n relativeParts.port = null;\n } else {\n return relative.build();\n }\n\n if (relativePath === basePath) {\n relativeParts.path = '';\n return relative.build();\n }\n\n // determine common sub path\n common = URI.commonPath(relativePath, basePath);\n\n // If the paths have nothing in common, return a relative URL with the absolute path.\n if (!common) {\n return relative.build();\n }\n\n var parents = baseParts.path\n .substring(common.length)\n .replace(/[^\\/]*$/, '')\n .replace(/.*?\\//g, '../');\n\n relativeParts.path = (parents + relativeParts.path.substring(common.length)) || './';\n\n return relative.build();\n };\n\n // comparing URIs\n p.equals = function(uri) {\n var one = this.clone();\n var two = new URI(uri);\n var one_map = {};\n var two_map = {};\n var checked = {};\n var one_query, two_query, key;\n\n one.normalize();\n two.normalize();\n\n // exact match\n if (one.toString() === two.toString()) {\n return true;\n }\n\n // extract query string\n one_query = one.query();\n two_query = two.query();\n one.query('');\n two.query('');\n\n // definitely not equal if not even non-query parts match\n if (one.toString() !== two.toString()) {\n return false;\n }\n\n // query parameters have the same length, even if they're permuted\n if (one_query.length !== two_query.length) {\n return false;\n }\n\n one_map = URI.parseQuery(one_query, this._parts.escapeQuerySpace);\n two_map = URI.parseQuery(two_query, this._parts.escapeQuerySpace);\n\n for (key in one_map) {\n if (hasOwn.call(one_map, key)) {\n if (!isArray(one_map[key])) {\n if (one_map[key] !== two_map[key]) {\n return false;\n }\n } else if (!arraysEqual(one_map[key], two_map[key])) {\n return false;\n }\n\n checked[key] = true;\n }\n }\n\n for (key in two_map) {\n if (hasOwn.call(two_map, key)) {\n if (!checked[key]) {\n // two contains a parameter not present in one\n return false;\n }\n }\n }\n\n return true;\n };\n\n // state\n p.preventInvalidHostname = function(v) {\n this._parts.preventInvalidHostname = !!v;\n return this;\n };\n\n p.duplicateQueryParameters = function(v) {\n this._parts.duplicateQueryParameters = !!v;\n return this;\n };\n\n p.escapeQuerySpace = function(v) {\n this._parts.escapeQuerySpace = !!v;\n return this;\n };\n\n return URI;\n}));\n", "import {Bid, OnlineBid} from \"./data_types_definitions\";\n\nexport enum WebcastStateEnum {\n WEBCAST_STATE__LOADING = -9,\n WEBCAST_STATE__LOBBY = 0,\n\n WEBCAST_STATE__BETWEEN_ROUNDS = 1,\n WEBCAST_STATE__DURING_ROUND_BIDDING = 2,\n WEBCAST_STATE__CHOICE_ROUND_LOTS_SELECT = 3,\n\n WEBCAST_STATE__ROUND_STOPPING_TRANSITIONAL = 15, // this state is only present on the client side, the server doesn't have it\n\n WEBCAST_STATE__CLOSED = 99,\n}\n\nexport const WEBCAST_STATES_MAP = Object.freeze(new Map([\n [WebcastStateEnum.WEBCAST_STATE__LOADING, 'Loading'],\n [WebcastStateEnum.WEBCAST_STATE__LOBBY, 'Lobby'],\n [WebcastStateEnum.WEBCAST_STATE__BETWEEN_ROUNDS, 'Running: Between rounds'],\n [WebcastStateEnum.WEBCAST_STATE__DURING_ROUND_BIDDING, 'Running: Round bidding'],\n [WebcastStateEnum.WEBCAST_STATE__CHOICE_ROUND_LOTS_SELECT, 'Running: Choice select lots'],\n [WebcastStateEnum.WEBCAST_STATE__CLOSED, 'Finished'],\n]));\n\n\n\nexport const LotStateEnum = Object.freeze({\n OPEN: -1,\n CLOSED_SOLD: 0,\n CLOSED_NO_SALE: 1,\n CLOSED_PENDING: 2\n});\n\n\nexport const LOT_STATES_MAP = Object.freeze(new Map([\n [LotStateEnum.OPEN, 'OPEN'],\n [LotStateEnum.CLOSED_SOLD, 'CLOSED_SOLD'],\n [LotStateEnum.CLOSED_NO_SALE, 'CLOSED_NO_SALE'],\n [LotStateEnum.CLOSED_PENDING, 'CLOSED_PENDING'],\n]));\n\n\n\nexport const RoundTypeEnum = Object.freeze({\n SINGLE_NORMAL: 11,\n SINGLE_BOXLOT: 12,\n GROUP_ONEMONEY: 21,\n GROUP_CHOICE: 22,\n GROUP_CHOICE_REOPEN: 23,\n GROUP_TIMESTHEMONEY: 25,\n});\n\n\nexport const ROUND_TYPES_MAP = Object.freeze(new Map([\n [RoundTypeEnum.SINGLE_NORMAL, 'SINGLE_NORMAL'],\n [RoundTypeEnum.SINGLE_BOXLOT, 'SINGLE_BOXLOT'],\n [RoundTypeEnum.GROUP_ONEMONEY, 'GROUP_ONEMONEY'],\n [RoundTypeEnum.GROUP_CHOICE, 'GROUP_CHOICE'],\n [RoundTypeEnum.GROUP_CHOICE_REOPEN, 'GROUP_CHOICE_REOPEN'],\n [RoundTypeEnum.GROUP_TIMESTHEMONEY, 'GROUP_TIMESTHEMONEY'],\n]));\n\nexport const ROUND_TYPES_SINGLE = Object.freeze([ RoundTypeEnum.SINGLE_NORMAL, RoundTypeEnum.SINGLE_BOXLOT ]);\nexport const ROUND_TYPES_GROUP = Object.freeze([ RoundTypeEnum.GROUP_ONEMONEY, RoundTypeEnum.GROUP_TIMESTHEMONEY, RoundTypeEnum.GROUP_CHOICE ]);\n\nexport const ROUND_TYPES_DISPLAY_NAMES_MAP = Object.freeze(new Map([\n [RoundTypeEnum.SINGLE_NORMAL, 'Single Lot'],\n [RoundTypeEnum.SINGLE_BOXLOT, 'Boxlot'],\n [RoundTypeEnum.GROUP_ONEMONEY, 'One-money'],\n [RoundTypeEnum.GROUP_TIMESTHEMONEY, 'Times the Money'],\n [RoundTypeEnum.GROUP_CHOICE, 'Choice'],\n [RoundTypeEnum.GROUP_CHOICE_REOPEN, 'Choice (re-open)'],\n]));\n\n\n\nexport enum RoundStopTypeEnum {\n CANCEL = -1,\n SOLD = 2,\n NO_SALE = 11,\n PENDING = 4,\n}\n\n\nexport const ROUND_STOP_TYPES_MAP = Object.freeze(new Map([\n [RoundStopTypeEnum.CANCEL, 'CANCEL'],\n [RoundStopTypeEnum.SOLD, 'SOLD'],\n [RoundStopTypeEnum.NO_SALE, 'NO_SALE'],\n [RoundStopTypeEnum.PENDING, 'PENDING'],\n]));\n\n\n\nexport const BidReviseTypeEnum = Object.freeze({\n REVERSE: -1,\n OVERRIDE_BY_FLOOR: 1,\n});\n\n\nexport function computeBidderDisplay(bid:Bid|OnlineBid):string {\n if (bid.bidderNo === '0' ) {\n return 'FLOOR';\n }\n else if (bid.bidderLabel && bid.bidderLabel.length) {\n return `${bid.bidderNo} (${bid.bidderLabel})`;\n }\n else {\n return bid.bidderNo\n }\n}\n\n\nexport function decorateBid(bid:T):T {\n if (bid) {\n return {\n ... bid,\n bidderDisplay: computeBidderDisplay(bid)\n }\n }\n else {\n return null\n }\n}\n", "import {createReducer} from \"@reduxjs/toolkit\";\nimport {ActionsCreators, ChannelEnum, WbsCommStatesEnum, WbsNetworkStatusConnectionStateEnum} from \"../actions\";\n\n\n\nexport type ReduxWebcastWbsNetworkStatusType = {\n wbsVersionBuildTag: string,\n connectionState: WbsNetworkStatusConnectionStateEnum,\n roundTripMilliseconds: number|false,\n biddingCommStatus: WbsCommStatesEnum,\n biddingCommBusy: boolean,\n chatCommStatus: WbsCommStatesEnum,\n chatCommBusy: boolean,\n}\n\n\nconst initialState:ReduxWebcastWbsNetworkStatusType = {\n connectionState: WbsNetworkStatusConnectionStateEnum.connecting,\n roundTripMilliseconds: -1,\n biddingCommStatus: WbsCommStatesEnum.WBS_COMM_STATUS_UNINITIALIZED,\n chatCommStatus: WbsCommStatesEnum.WBS_COMM_STATUS_UNINITIALIZED,\n biddingCommBusy: null,\n chatCommBusy: null,\n wbsVersionBuildTag: null,\n};\n\n/**\n * combined as `wbsNetworkStatus`\n *\n *\n * ===\n * action: WEBCAST_AUCTION_INIT\n * payload: null\n *\n *\n * ===\n * action: WEBCAST_AUCTION_CLEAR\n * payload: null\n *\n *\n * ===\n * action: WEBCAST_AUCTION_DATA_SNAPSHOT_INIT\n * payload: {\n * wbsVersionBuildTag: string\n * }\n *\n *\n * ==\n * action: WEBCAST_WBS_NETWORK_STATUS_UPDATE\n * payload: WbsNetworkStatusUpdatePayloadType {\n * connected: boolean\n * roundTripMilliseconds: number|false\n * }\n *\n * ===\n * action: WEBCAST_WBS_COMM_STATE_UPDATE\n * payload: WbsCommStateUpdatePayloadType {\n * channel: 'bidding'|'chat'\n * newStatus: 'sending'|'idle' // WbsCommStatesEnum\n * }\n *\n *\n *\n * @param state\n * @param action\n * @returns ReduxWebcastWbsNetworkStatusType {{\n * connected: boolean,\n * roundTripMilliseconds:?number,\n * biddingCommStatus: string,\n * biddingCommBusy: boolean,\n * chatCommStatus: string,\n * chatCommBusy: boolean,\n * }}\n */\nconst reducerWbsNetworkStatus = createReducer(initialState, (builder) => {\n\n builder.addCase(ActionsCreators.webcast.webcastAuctionInit, (state, action) => {\n state.biddingCommStatus = WbsCommStatesEnum.WBS_COMM_STATUS_INITIALIZED;\n state.biddingCommBusy = true;\n state.chatCommStatus = WbsCommStatesEnum.WBS_COMM_STATUS_INITIALIZED;\n state.chatCommBusy = true;\n });\n\n\n builder.addCase(ActionsCreators.webcast.webcastAuctionClear, (state, action) => {\n state.biddingCommStatus = WbsCommStatesEnum.WBS_COMM_STATUS_UNINITIALIZED;\n state.biddingCommBusy = true;\n state.chatCommStatus = WbsCommStatesEnum.WBS_COMM_STATUS_UNINITIALIZED;\n state.chatCommBusy = true;\n });\n\n\n builder.addCase(ActionsCreators.webcast.webcastAuctionDataSnapshotInit, (state, action) => {\n state.wbsVersionBuildTag = action.payload.wbsVersionBuildTag;\n });\n\n\n builder.addCase(ActionsCreators.webcast.wbsNetworkStatusUpdate, (state, action) => {\n const { connectionState, roundTripMilliseconds } = action.payload;\n state.connectionState = connectionState;\n state.roundTripMilliseconds = roundTripMilliseconds;\n });\n\n builder.addCase(ActionsCreators.webcast.wbsCommStateUpdate, (state, action) => {\n const { channel, newStatus } = action.payload;\n const isBusyStatus = newStatus !== WbsCommStatesEnum.WBS_COMM_STATUS_IDLE;\n if (channel === ChannelEnum.bidding) {\n state.biddingCommStatus = newStatus;\n state.biddingCommBusy = isBusyStatus;\n }\n else if (channel === ChannelEnum.chat) {\n state.chatCommStatus = newStatus;\n state.chatCommBusy = isBusyStatus;\n }\n else {\n // '*' all channels\n state.biddingCommStatus = newStatus;\n state.biddingCommBusy = isBusyStatus;\n state.chatCommStatus = newStatus;\n state.chatCommBusy = isBusyStatus;\n }\n });\n\n});\n\n\nexport default reducerWbsNetworkStatus;\n", "import {createReducer} from \"@reduxjs/toolkit\";\nimport {ActionsCreators, CurrentRoundCloseActionPayloadType, CurrentRoundStopActionPayloadType} from \"../actions\";\nimport {PMAuctionDataSnapshot, PMWebcastStatusChanged,} from \"../../data/data_types_definitions\";\nimport {RoundTypeEnum, WebcastStateEnum} from \"../../data/WebcastDataDomain\";\nimport {isDevelopmentEnv} from \"../../../utilities\";\n\n\nexport type ReduxWebcastStatusType = {\n state: WebcastStateEnum,\n paused: boolean,\n biddingFunctionsEnabled: boolean\n};\n\n\n\nconst initialState = {\n state: WebcastStateEnum.WEBCAST_STATE__LOADING,\n paused: false,\n biddingFunctionsEnabled: false,\n};\n\n\n/**\n * combined as `webcastStatus`\n *\n * ===\n * action: WEBCAST_AUCTION_INIT\n * payload: {\n * state: number,\n * paused: boolean,\n * biddingFunctionsEnabled: boolean\n * }\n *\n *\n * ===\n * action: WEBCAST_AUCTION_DATA_SNAPSHOT_INIT\n * payload: {\n * state: number,\n * paused: boolean,\n * biddingFunctionsEnabled: boolean\n * }\n *\n *\n * ===\n * action: WEBCAST_STATUS_CHANGE\n * payload: {\n * started?\n * closed?\n * paused?\n * }\n *\n *\n * ===\n * action: WEBCAST_CURRENT_ROUND_BIDDING_UPDATE\n * payload: *\n *\n *\n *\n * ===\n * action: WEBCAST_CURRENT_ROUND_STOP\n * payload: {\n * roundId: string // uuid\n * roundType: number\n * stopType: integer // see RoundStopTypeEnum\n * }\n *\n *\n * ===\n * action: WEBCAST_CURRENT_ROUND_CLOSE\n * payload: {\n * roundId: string // uuid\n * stopType: integer // see RoundStopTypeEnum\n * nextRound: ?\n * }\n *\n *\n *\n * @param state\n * @param action\n * @returns {{\n * state: number\n * paused: boolean,\n * biddingFunctionsEnabled: boolean\n * }}\n */\n\n\nconst reducerWebcastStatus = createReducer(initialState, (builder) => {\n\n builder.addCase(ActionsCreators.webcast.webcastAuctionInit, (state, action) => {\n state.state = WebcastStateEnum.WEBCAST_STATE__LOADING;\n state.paused = false;\n state.biddingFunctionsEnabled = false;\n });\n\n\n builder.addCase(ActionsCreators.webcast.webcastAuctionClear, (state, action) => {\n state.state = WebcastStateEnum.WEBCAST_STATE__LOADING;\n state.paused = false;\n state.biddingFunctionsEnabled = false;\n });\n\n\n builder.addCase(ActionsCreators.webcast.webcastAuctionDataSnapshotInit, (state, action) => {\n const payload: PMAuctionDataSnapshot = action.payload;\n state.state = payload.webcastState;\n state.paused = payload.webcastIsPaused;\n state.biddingFunctionsEnabled = (payload.webcastState > WebcastStateEnum.WEBCAST_STATE__LOBBY && !payload.webcastIsPaused) // must be out of LOBBY and must not be paused\n });\n\n\n builder.addCase(ActionsCreators.webcast.webcastAuctionDataLotsDetailsUpdate, (state, action) => {\n if (action.payload?.isDataSync) {\n // unpause after a data sync\n state.paused = false;\n state.biddingFunctionsEnabled = state.state !== WebcastStateEnum.WEBCAST_STATE__LOBBY\n }\n });\n\n\n builder.addCase(ActionsCreators.webcast.webcastStatusChange, (state, action) => {\n const payload: PMWebcastStatusChanged = action.payload;\n\n if (payload.started) {\n state.state = WebcastStateEnum.WEBCAST_STATE__BETWEEN_ROUNDS;\n state.paused = false;\n state.biddingFunctionsEnabled = true;\n }\n else if (payload.closed) {\n state.state = WebcastStateEnum.WEBCAST_STATE__CLOSED;\n state.paused = false;\n state.biddingFunctionsEnabled = false;\n }\n else if (payload.paused !== undefined) {\n state.paused = !!payload.paused;\n state.biddingFunctionsEnabled = !payload.paused;\n }\n });\n\n\n builder.addCase(ActionsCreators.webcast.webcastCurrentRoundBiddingUpdate, (state, action) => {\n state.state = WebcastStateEnum.WEBCAST_STATE__DURING_ROUND_BIDDING\n });\n\n\n builder.addCase(ActionsCreators.webcast.webcastCurrentRoundStop, (state, action) => {\n const payload: CurrentRoundStopActionPayloadType = action.payload;\n if (payload.isTransitional) {\n state.state = WebcastStateEnum.WEBCAST_STATE__ROUND_STOPPING_TRANSITIONAL\n }\n else {\n // NOT transitional\n\n // if nextRound is missing, then currentRound is CHOICE and it's stopped as SOLD|PENDING => CHOICE_LOTS_SELECT\n if ( ! payload.nextRound) {\n state.state = WebcastStateEnum.WEBCAST_STATE__CHOICE_ROUND_LOTS_SELECT\n }\n else {\n // *not* a CHOICE round stopped SOLD|PENDING\n // don't change any status, it will get changed later with ROUND_CLOSE\n }\n }\n\n });\n\n builder.addCase(ActionsCreators.webcast.webcastCurrentRoundClose, (state, action) => {\n const payload:CurrentRoundCloseActionPayloadType = action.payload;\n // payload for ROUND_CLOSE must have the `nextRound` present\n if (isDevelopmentEnv) {\n if (!payload.nextRound) {\n throw new Error('reducerWebcastStatus: WEBCAST_CURRENT_ROUND_CLOSE: nextRound may not be null');\n }\n }\n\n if (payload.nextRound.roundType === RoundTypeEnum.GROUP_CHOICE_REOPEN) {\n state.state = WebcastStateEnum.WEBCAST_STATE__CHOICE_ROUND_LOTS_SELECT;\n }\n else {\n state.state = WebcastStateEnum.WEBCAST_STATE__BETWEEN_ROUNDS;\n }\n });\n});\n\nexport default reducerWebcastStatus;\n", "import {ActionsCreators, CurrentRoundCloseActionPayloadType} from \"../actions\";\nimport {Bid, Lot, LotDetails, PMAuctionDataSnapshot, PMLotsPassClosed, Round} from \"../../data/data_types_definitions\";\nimport {decorateBid, LotStateEnum, RoundStopTypeEnum, RoundTypeEnum} from \"../../data/WebcastDataDomain\";\nimport {createReducer} from \"@reduxjs/toolkit\";\n\nexport type ReduxWebcastAuctionDataType = {\n auctionId: number,\n auctionName: string,\n lots: Array,\n lotsMapById: Map,\n closedRounds: Array,\n\n // clerk only\n remoteLotsCacheKeyOutOfSync?: string|null // 'list'|'details'|'media_files'|null\n}\n\n\n\nconst initialState:ReduxWebcastAuctionDataType = {\n auctionId: null,\n auctionName: null,\n lots: [],\n lotsMapById: new Map(),\n closedRounds: [],\n};\n\n\n// png: 150x100 bg:#ccc round corners\nconst LOT_IMAGE_PLACEHOLDER_SRC = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAJYAAABkCAQAAADOUgF7AAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAAAmJLR0QA/4ePzL8AAAAHdElNRQfjBBkVGwepKkL7AAABkElEQVR42u3UMUpDQRhF4X9GIQHRbMDaQlSwUNOmDG4hfbASV+MCzBasbcVoIaayjgswpniGwNhb5VSTB+dbweUUN0VEfHYW4xiV47QX+qes0qxMlveDJiJFPB/uPKaz2qO23Gw97M/TZ+f7xVQb+Di4yIuxqTZyurjJMaq9oi3KKE2X3vqGmmyqjXVz7QVtYizAWICxAGMBxgKMBRgLMBZgLMBYgLEAYwHGAowFGAswFmAswFiAsQBjAcYCjAUYCzAWYCzAWICxAGMBxgKMBRgLMBZgLMBYgLEAYwHGAowFGAswFmAswFiAsQBjAcYCjAUYCzAWYCzAWICxAGMBxgKMBRgLMBZgLMBYgLEAYwHGAowFGAswFmAswFiAsQBjAcYCjAUYCzAWYCzAWICxAGMBxgKMBRgLMBZgLMBYgLEAYwHGAowF5LKqPaE1mpxmtTe0RZnlMqk9oi3SQ3rq7k/jpPaQ7Vfee1d50KyH8VF7yrYr77vXR785oj//uYy78hZN7UlbqSmvcdu7Ov+K+ANZ4DibiMdZIAAAACV0RVh0ZGF0ZTpjcmVhdGUAMjAxOS0wNC0yNlQwNjoyNzowNyswOTowMBgt5a8AAAAldEVYdGRhdGU6bW9kaWZ5ADIwMTktMDQtMjZUMDY6Mjc6MDcrMDk6MDBpcF0TAAAAAElFTkSuQmCC';\n\n\n\n\n/**\n * combined as `webcastAuctionData`\n *\n *\n *\n * ===\n * action: WEBCAST_AUCTION_INIT\n * payload: {\n * auctionId: number,\n * auctionName: number,\n * }\n *\n *\n *\n * ===\n * action: WEBCAST_AUCTION_CLEAR\n * payload: null\n *\n *\n *\n * ===\n * action: WEBCAST_AUCTION_DATA_SNAPSHOT_INIT\n * payload: {\n * lots: Array,\n * remoteLotsCacheKeyOutOfSync: string,\n * closedRounds: [],\n * currentRound: ?Round\n * }\n *\n *\n * ==\n * action: WEBCAST_CLERK_AUCTION_DATA_SYNC_CHECK_STATUS_UPDATE // used by \"sync lots from Rails\", update clerk-only info\n * payload: null|'list'|'details'|'media_files' // the outOfSync cache key\n *\n *\n * ==\n * action: WEBCAST_AUCTION_DATA_SYNC_LOTS_LIST_UPDATE // used by \"sync lots from Rails\"\n * payload: Array // new list of lots\n *\n * ==\n * action: WEBCAST_AUCTION_DATA_LOTS_DETAILS_UPDATE // lots description, images\n * payload: Array\n *\n *\n * ===\n * action: WEBCAST_CURRENT_ROUND_CLOSE\n * payload: {\n * stopType: number\n * }\n *\n *\n * ===\n * action: WEBCAST_LOTS_PASS_CLOSE\n * payload: {\n * lotsIds: Array\n * }\n *\n *\n *\n *\n * @param state\n * @param action\n * @returns {{\n * lots: Array\n * lotsMapById: Map\n * closedRounds: Array\n * }}\n */\nconst reducerWebcastAuctionData = createReducer(initialState, (builder) => {\n\n builder.addCase(ActionsCreators.webcast.webcastAuctionClear, (state, action) => {\n return initialState;\n });\n\n\n builder.addCase(ActionsCreators.webcast.webcastAuctionInit, (state, action) => {\n state.auctionId = action.payload.auctionId;\n state.auctionName = action.payload.auctionName;\n state.lots = [];\n state.lotsMapById = new Map();\n state.closedRounds = [];\n });\n\n\n builder.addCase(ActionsCreators.webcast.webcastAuctionDataSnapshotInit, (state, action) => {\n const payload:PMAuctionDataSnapshot = action.payload;\n const lots = payload.lots.map((lot) => {\n return {\n name: '...',\n defaultImageSmUrl: LOT_IMAGE_PLACEHOLDER_SRC,\n ... lot\n }\n });\n\n state.auctionId = payload.auctionId;\n state.auctionName = payload.auctionName;\n state.lots = lots;\n state.lotsMapById = new Map(lots.map((lot) => [lot.id, lot]));\n state.closedRounds = payload.closedRounds.map((payloadRound:Round):Round => {\n const bidsHistoryLength:number = (payloadRound.bidsHistory && payloadRound.bidsHistory.length) || 0;\n const highestBid:Bid = bidsHistoryLength > 0 ? payloadRound.bidsHistory[bidsHistoryLength-1] : null;\n return {\n ... payloadRound,\n highestBid: decorateBid(highestBid),\n }\n });\n\n state.remoteLotsCacheKeyOutOfSync = payload.remoteLotsCacheKeyOutOfSync;\n });\n\n\n builder.addCase(ActionsCreators.webcast.webcastClerkAuctionDataSyncCheckStatusUpdate, (state, action) => {\n if (action.payload === true) {\n // sync was just applied\n state.remoteLotsCacheKeyOutOfSync = null;\n }\n else {\n // sync check result\n state.remoteLotsCacheKeyOutOfSync = action.payload;\n }\n });\n\n\n builder.addCase(ActionsCreators.webcast.webcastAuctionDataSyncLotsListUpdate, (state, action) => {\n const syncedLots = action.payload.map((payloadLot:Lot) => {\n let syncedLot:Lot;\n\n const existingLot:Lot = state.lotsMapById.get(payloadLot.id);\n if (existingLot) {\n // existing lot\n syncedLot = {\n ... existingLot,\n orderIdx: payloadLot.orderIdx,\n }\n }\n else {\n // new lot\n syncedLot = {\n name: '...',\n defaultImageSmUrl: LOT_IMAGE_PLACEHOLDER_SRC,\n ... payloadLot\n }\n }\n\n return syncedLot;\n });\n\n state.lots = syncedLots;\n state.lotsMapById = new Map(syncedLots.map((lot) => [lot.id, lot]));\n });\n\n\n builder.addCase(ActionsCreators.webcast.webcastAuctionDataLotsDetailsUpdate, (state, action) => {\n const lotsUpdated = state.lots.map((lot) => {\n let lotExtra:LotDetails = action.payload.lotsDetails.find((ld) => lot.id === ld.id);\n // WARNING: `lotExtra` may be null, when lots have been deleted on Rails after WBS prepare\n lotExtra = lotExtra || { name: 'REMOVED FROM AUCTION' };\n const firstLotImage = lotExtra.images && lotExtra.images[0];\n return {\n ... lot,\n ... lotExtra,\n defaultImageSmUrl: firstLotImage && firstLotImage.smUrl || LOT_IMAGE_PLACEHOLDER_SRC,\n }\n });\n\n state.lots = lotsUpdated;\n state.lotsMapById = new Map(lotsUpdated.map((lot) => [lot.id, lot]));\n });\n\n\n builder.addCase(ActionsCreators.webcast.webcastCurrentRoundClose, (state, action) => {\n return handleAction_CURRENT_ROUND_CLOSE(state, action.payload);\n });\n\n\n builder.addCase(ActionsCreators.webcast.webcastLotsPassClose, (state, action) => {\n return handleAction_LOTS_PASS_CLOSE(state, action.payload);\n });\n\n\n builder.addDefaultCase((state, action) => {return state});\n\n});\n\nexport default reducerWebcastAuctionData;\n\n\n\nconst ROUND_STOP_TO_LOT_STATE_MAPPING = new Map([\n [RoundStopTypeEnum.CANCEL, LotStateEnum.OPEN],\n [RoundStopTypeEnum.NO_SALE, LotStateEnum.CLOSED_NO_SALE],\n [RoundStopTypeEnum.PENDING, LotStateEnum.CLOSED_PENDING],\n [RoundStopTypeEnum.SOLD, LotStateEnum.CLOSED_SOLD],\n]);\n\n\n\n\nfunction handleAction_CURRENT_ROUND_CLOSE(state:ReduxWebcastAuctionDataType, payload:CurrentRoundCloseActionPayloadType):ReduxWebcastAuctionDataType {\n\n if (payload.stopType === RoundStopTypeEnum.CANCEL) {\n // do nothing if this is a canceled round\n return state;\n }\n\n\n const lotCloseState = ROUND_STOP_TO_LOT_STATE_MAPPING.get(payload.stopType);\n\n const closedRounds:Array = [];\n let closedLotsIds:Array = [];\n\n if (payload.roundType === RoundTypeEnum.GROUP_CHOICE || payload.roundType === RoundTypeEnum.GROUP_CHOICE_REOPEN) {\n\n if (payload.stopType === RoundStopTypeEnum.NO_SALE) {\n closedLotsIds = payload.lotsIds;\n }\n else {\n // stopType is SOLD|PENDING\n\n const userLotsSelection: Map> = new Map();\n\n payload.choiceLotsIds && payload.choiceLotsIds.forEach((lotId, idx) => {\n const userId = payload.choiceUsersIds[idx];\n if (userId === 0) {\n // participantId==0 means unselected; skip lots that were mark unselected\n return\n }\n\n let userSelection: Array = userLotsSelection.get(userId);\n if (!userSelection) {\n userSelection = [];\n userLotsSelection.set(userId, userSelection);\n }\n userSelection.push(lotId);\n\n closedLotsIds.push(lotId);\n });\n\n userLotsSelection.forEach((selectedLotsIds, userId) => {\n const highestBid: Bid = {...payload.highestBid, userId};\n // hack: we need bidderNumber and bidderLabel if we want to display this on the bidder side\n\n closedRounds.push({\n roundId: payload.roundId,\n roundType: payload.roundType,\n lotsIds: selectedLotsIds,\n stopType: payload.stopType,\n bidsHistory: [...payload.bidsHistory, highestBid],\n highestBid: decorateBid(highestBid),\n });\n });\n }\n }\n else {\n\n // not a CHOICE|CHOICE_REOPEN => just one round has closed\n\n closedRounds.push({\n roundId: payload.roundId,\n roundType: payload.roundType,\n lotsIds: payload.lotsIds,\n stopType: payload.stopType,\n bidsHistory: payload.bidsHistory,\n highestBid: decorateBid(payload.highestBid),\n });\n\n closedLotsIds = payload.lotsIds;\n }\n\n let stateClosedRounds: Array = state.closedRounds.map( (closedRound:Round): Round => {\n return {\n ...closedRound,\n lotsIds: closedRound.lotsIds.filter(lotId => !closedLotsIds.includes(lotId))\n }\n }).filter(r => r.lotsIds.length > 0);\n\n\n const lots = state.lots.map((lot) => {\n if (closedLotsIds.includes(lot.id)) {\n return {\n ... lot,\n state: lotCloseState\n }\n }\n else {\n // not part of closedLots list, then leave untouched\n return lot;\n }\n });\n\n\n\n return {\n ...state,\n lots: lots,\n lotsMapById: new Map(lots.map((lot) => [lot.id, lot])),\n closedRounds: [ ...stateClosedRounds, ...closedRounds ]\n }\n}\n\n\n\n\n\n\nfunction handleAction_LOTS_PASS_CLOSE(state:ReduxWebcastAuctionDataType, payload:PMLotsPassClosed):ReduxWebcastAuctionDataType {\n\n if (! payload.noSaleRound) {\n // do nothing\n return state;\n }\n\n const closedRound:Round = payload.noSaleRound;\n\n const lots = state.lots.map((lot) => {\n if (closedRound.lotsIds.includes(lot.id)) {\n return {\n ... lot,\n state: LotStateEnum.CLOSED_NO_SALE\n }\n }\n else {\n // not part of lots to close, then leave untouched\n return lot;\n }\n });\n\n return {\n ...state,\n lots: lots,\n lotsMapById: new Map(lots.map((lot) => [lot.id, lot])),\n closedRounds: [ closedRound, ... state.closedRounds ],\n }\n}\n\n", "import {ACTION_TYPES, CurrentRoundCloseActionPayloadType, CurrentRoundStopActionPayloadType} from \"../actions\";\nimport {PMAuctionDataSnapshot, ReduxAction, Round} from \"../../data/data_types_definitions\";\nimport {RoundTypeEnum} from \"../../data/WebcastDataDomain\";\n\n\nexport type ReduxWebcastCurrentRoundType = {\n roundId?: string,\n roundType: number,\n lotsIds: Array,\n stopType?: number,\n};\n\n\n\nconst initialState:ReduxWebcastCurrentRoundType = {\n roundId: null,\n roundType: null,\n lotsIds: null,\n stopType: null,\n};\n\n\n/**\n * combined as `webcastCurrentRound`\n *\n *\n * ===\n * action: WEBCAST_AUCTION_DATA_SNAPSHOT_INIT\n * payload: {\n * currentRound: {\n * roundId: string // uuid\n * roundType:\n * lotsIds:\n * }\n * }\n *\n *\n * ===\n * action: WEBCAST_CURRENT_ROUND_CREATE\n * payload: {\n * roundId: string // uuid\n * roundType:\n * lotsIds:\n * }\n *\n *\n * ===\n * action: WEBCAST_CURRENT_ROUND_STOP\n * payload: CurrentRoundStopActionPayloadType {\n * roundId: string // uuid\n * roundType: number\n * stopType: integer // see RoundStopTypeEnum\n * isTransitional: boolean\n * }\n *\n *\n * ===\n * action: WEBCAST_CURRENT_ROUND_CLOSE\n * payload: CurrentRoundCloseActionPayloadType {\n * stopType: number\n * nextRound: ?\n * }\n *\n *\n * @param state\n * @param action\n * @returns ReduxWebcastCurrentRoundType {{\n * roundId: string\n * roundType: number\n * lotsIds: Array\n * stopType: ?number\n * }}\n */\nexport default function reducerWebcastCurrentRound(state:ReduxWebcastCurrentRoundType = initialState, action:ReduxAction):ReduxWebcastCurrentRoundType {\n if (action.error) {\n return state;\n }\n\n\n\n switch(action.type) {\n\n case ACTION_TYPES.WEBCAST_AUCTION_INIT: {\n return initialState;\n }\n\n\n\n case ACTION_TYPES.WEBCAST_AUCTION_DATA_SNAPSHOT_INIT:\n return handleAction_SALE_DATA_SNAPSHOT_INIT(state, action.payload);\n\n\n case ACTION_TYPES.WEBCAST_CURRENT_ROUND_CREATE: {\n const payloadRound:Round = action.payload;\n return {\n ...payloadRound,\n stopType: undefined,\n }\n }\n\n\n case ACTION_TYPES.WEBCAST_CURRENT_ROUND_STOP: {\n const payload: CurrentRoundStopActionPayloadType = action.payload;\n return {\n ... state,\n stopType: payload.stopType,\n }\n }\n\n case ACTION_TYPES.WEBCAST_CURRENT_ROUND_CLOSE: {\n // ROUND_CLOSE always has a `nextRound`\n const payload:CurrentRoundCloseActionPayloadType = action.payload;\n const payloadNextRound:Round = payload.nextRound;\n return {\n roundId: payloadNextRound.roundId,\n roundType: payloadNextRound.roundType,\n lotsIds: payloadNextRound.lotsIds,\n stopType: payloadNextRound.roundType === RoundTypeEnum.GROUP_CHOICE_REOPEN ? payloadNextRound.stopType : undefined, // if nextRound is CHOICE_REOPEN, it's already stopped\n }\n }\n\n\n }//switch\n\n\n return state;\n}\n\n\n\n\n\n\nfunction handleAction_SALE_DATA_SNAPSHOT_INIT(state:ReduxWebcastCurrentRoundType, payload:PMAuctionDataSnapshot):ReduxWebcastCurrentRoundType {\n const payloadCurrentRound:Round = payload && payload.currentRound;\n\n if (payloadCurrentRound) {\n // remove the `bidsHistory` attribute: https://stackoverflow.com/a/53443378/317884\n return (({ bidsHistory, ...newState }:Round) => newState)(payloadCurrentRound);\n }\n return state;\n}\n\n", "import {ACTION_TYPES, CurrentRoundCloseActionPayloadType, CurrentRoundStopActionPayloadType} from \"../actions\";\nimport {\n Bid,\n PMBiddingUpdated,\n PMChoiceLotsSelected,\n PMAuctionDataSnapshot,\n OnlineBid,\n ReduxAction,\n Round\n} from \"../../data/data_types_definitions\";\nimport {BidReviseTypeEnum, RoundStopTypeEnum, RoundTypeEnum, decorateBid} from \"../../data/WebcastDataDomain\";\nimport {WebcastAuctionConnectData_TypeDef} from \"../../services/AuctionsManager\";\n\n\nexport type ReduxWebcastCurrentRoundBiddingType = {\n myUserId?: number,\n myUserRole?: string,\n\n roundId: string,\n\n firstOnlineBid?: OnlineBid,\n secondOnlineBid?: OnlineBid,\n\n askingBidValue?: number,\n bidIncrement?: number,\n bidsHistory?: Array,\n\n highestBid?: Bid,\n\n stopType?: number,\n\n choiceLotsSelection?: Array<[number, number]>, // Array<[lotId, participantId]>\n choiceLotsSelectionMap?: Map, // Map\n choiceSelectionSubmitted?: boolean,\n};\n\n\n\nconst initialResetState:ReduxWebcastCurrentRoundBiddingType = {\n // ! do not include fields that *should* be kept during new reducer runs (fields like myUserId, myUserRole)\n roundId: null,\n firstOnlineBid: null,\n secondOnlineBid: null,\n askingBidValue: null,\n bidIncrement: null,\n highestBid: null,\n bidsHistory: null,\n choiceLotsSelection: null,\n choiceLotsSelectionMap: new Map(),\n choiceSelectionSubmitted: false,\n};\n\n/**\n * combined as `webcastCurrentRoundBidding`\n *\n *\n * ===\n * action: WEBCAST_AUCTION_DATA_SNAPSHOT_INIT\n * payload: {\n * currentRound: {\n * roundId: string // uuid\n * roundType:\n * lotsIds:\n * bidsHistory: Array [\n * {\n * value: integer\n * bidderNumber: string\n * bidderLabel: string\n * overridden: boolean\n * participantId: integer // CLERK only\n * },\n * ....\n * ]\n * }\n *\n * askingBidValue: integer\n *\n * highestBid: {\n * value: integer\n * bidderNumber: string\n * bidderLabel: string\n * participantId: integer // CLERK only\n * }\n * }\n *\n *\n * ===\n * action: WEBCAST_CURRENT_ROUND_CREATE\n * payload: {\n * roundId: string // uuid\n * roundType:\n * lotsIds:\n * }\n *\n *\n * ===\n * action: WEBCAST_CURRENT_ROUND_BIDDING_UPDATE\n * payload: {\n * roundId: string // uuid\n *\n * askingBidValue?: integer\n * bidIncrement?: number,\n *\n * highestBid?: {\n * value: number // cents\n * bidderNumber: string\n * bidderLabel: string\n * participantId: number // CLERK only\n * }\n * }\n *\n *\n *\n * ===\n * action: WEBCAST_CURRENT_ROUND_STOP\n * payload: CurrentRoundStopActionPayloadType {\n * roundId: string // uuid\n * roundType: number\n * stopType: integer // see RoundStopTypeEnum\n * isTransitional: boolean\n * }\n *\n *\n * ===\n * action: WEBCAST_CURRENT_ROUND_CLOSE\n * payload: CurrentRoundCloseActionPayloadType {\n * roundId: string // uuid\n *\n * stopType: integer // see RoundStopTypeEnum\n *\n * nextRound: ? {\n * roundId:\n * roundType:\n * lotsIds:\n * firstOnlineBid:\n * secondOnlineBid:\n * }\n *\n * choiceLotsAssigned: Array\n * }\n *\n *\n * ===\n * action: WEBCAST_CHOICE_LOTS_SELECTION_UPDATE\n * payload: {\n * roundId: string\n * choiceLotsIds: Array\n * choiceUsersIds: Array\n * }\n *\n *\n * @param state\n * @param action\n * @returns ReduxWebcastCurrentRoundBiddingType {{\n * roundId: string\n *\n * firstOnlineBid?: OnlineBid\n * secondOnlineBid?: OnlineBid\n *\n * askingBidValue: number\n * bidIncrement: number\n * bidsHistory: Array\n *\n * highestBid: // { value, bidderNumber, bidderLabel, participantId }\n *\n * stopType?: number\n *\n * choiceLotsSelection?: Array<[number, number]> // Array<[lotId, participantId]>\n * choiceLotsSelectionMap?: Map // Map\n * choiceSelectionSubmitted?: boolean\n * }}\n */\nexport default function reducerWebcastCurrentRoundBidding(state:ReduxWebcastCurrentRoundBiddingType = initialResetState, action:ReduxAction):ReduxWebcastCurrentRoundBiddingType {\n if (action.error) {\n return state;\n }\n\n\n switch(action.type) {\n\n case ACTION_TYPES.WEBCAST_AUCTION_INIT: {\n const saleConnectData:WebcastAuctionConnectData_TypeDef = action.payload;\n return {\n ... initialResetState,\n myUserId: saleConnectData.participantId,\n myUserRole: saleConnectData.participantRole,\n };\n }\n\n\n case ACTION_TYPES.WEBCAST_AUCTION_DATA_SNAPSHOT_INIT:\n return handleAction_SALE_DATA_SNAPSHOT_INIT(state, action.payload);\n\n\n case ACTION_TYPES.WEBCAST_CURRENT_ROUND_CREATE: {\n return {\n ... state,\n ... initialResetState,\n ... computeHighestOnlineBidsSubState(action.payload),\n roundId: action.payload.roundId,\n }\n }\n\n\n case ACTION_TYPES.WEBCAST_CURRENT_ROUND_BIDDING_UPDATE:\n return handleAction_CURRENT_ROUND_BIDDING_UPDATE(state, action.payload);\n\n\n\n case ACTION_TYPES.WEBCAST_CURRENT_ROUND_STOP: {\n const payload:CurrentRoundStopActionPayloadType = action.payload;\n if (payload.isTransitional) {\n\n if (payload.choiceLotsIds && payload.choiceLotsIds.length) {\n // a CHOICE|CHOICE_REOPEN is closing, we need to have selection to show it in the screens\n const choiceLotsSelection:Array<[number, number]> = payload.choiceLotsIds.map((lotId, idx) => [lotId, payload.choiceUsersIds[idx]]);\n return {\n ... state,\n stopType: payload.stopType,\n choiceLotsSelection: choiceLotsSelection,\n choiceLotsSelectionMap: new Map(choiceLotsSelection),\n choiceSelectionSubmitted: false,\n }\n }\n\n // non-CHOICE is stopping\n return {\n ... state,\n stopType: payload.stopType,\n }\n }\n else {\n // not a transitional state\n if (payload.nextRound) {\n // non-CHOICE round is stopping, do nothing\n return state;\n }\n else {\n // a Choice round is stopping\n return {\n ... state,\n stopType: payload.stopType,\n choiceLotsSelection: [],\n choiceLotsSelectionMap: new Map(),\n choiceSelectionSubmitted: false,\n };\n }\n }\n }\n\n\n\n case ACTION_TYPES.WEBCAST_CURRENT_ROUND_CLOSE: {\n const payload:CurrentRoundCloseActionPayloadType = action.payload;\n\n if (payload.stopType === RoundStopTypeEnum.CANCEL) {\n return {\n ... state,\n ... initialResetState,\n roundId: payload.nextRound.roundId,\n\n ... computeHighestOnlineBidsSubState(payload.nextRound),\n }\n }\n else {\n const payloadNextRound:Round = payload.nextRound;\n\n if (payloadNextRound.roundType === RoundTypeEnum.GROUP_CHOICE_REOPEN) {\n // CHOICE_REOPEN for nextRound\n const bidsHistory = payloadNextRound.bidsHistory.map(bid => decorateBid(bid));\n return {\n ... state,\n ... initialResetState,\n roundId: payloadNextRound.roundId,\n stopType: payloadNextRound.stopType, // this type of round is already stopped\n bidsHistory: bidsHistory,\n highestBid: bidsHistory[bidsHistory.length - 1], // there's actually only one bid in the history\n ... computeHighestOnlineBidsSubState(payloadNextRound),\n }\n }\n else {\n // not a CHOICE_REOPEN nextRound\n return {\n ... state,\n ... initialResetState,\n roundId: payloadNextRound.roundId,\n ... computeHighestOnlineBidsSubState(payloadNextRound),\n }\n }\n }\n }\n\n\n\n case ACTION_TYPES.WEBCAST_CHOICE_LOTS_SELECTION_UPDATE: {\n const payload:PMChoiceLotsSelected = action.payload;\n\n if ( ! (payload && payload.choiceLotsIds && payload.choiceLotsIds.length)) {\n // do nothing if there's no valid payload -- should NOT get here!\n return state;\n }\n\n // build a helper Map with existing selection, to preserve un-changed entries\n const existingSelection = [ ...(state.choiceLotsSelection || []) ];\n const existingSelectionMap:Map = new Map(existingSelection);\n payload.choiceLotsIds.forEach((payloadLotId, idx) => {\n const payloadUserId = payload.choiceUsersIds[idx];\n existingSelectionMap.set(payloadLotId, payloadUserId);\n });\n\n const updatedChoiceLotsSelection = [];\n let choiceSelectionSubmitted = false;\n existingSelectionMap.forEach((userId, lotId) => {\n updatedChoiceLotsSelection.push([lotId, userId]);\n if (userId === state.myUserId) {\n // if our participantId is in the selection, then we've submitted our selection\n choiceSelectionSubmitted = true;\n }\n });\n\n\n return {\n ... state,\n choiceLotsSelection: updatedChoiceLotsSelection,\n choiceLotsSelectionMap: new Map(updatedChoiceLotsSelection),\n choiceSelectionSubmitted: choiceSelectionSubmitted,\n }\n\n }\n\n }// switch\n\n return state;\n};\n\n\n\n\n\n\n\nfunction transformApiBidsHistory(bids:Array):Array {\n if (bids?.length) {\n return bids.map((bid) => decorateBid(bid));\n }\n else {\n return null\n }\n}\n\n\nfunction computeHighestOnlineBidsSubState(round:Round):Pick {\n return {\n firstOnlineBid: decorateBid(round.firstOnlineBid),\n secondOnlineBid: decorateBid(round.secondOnlineBid),\n }\n}\n\n\n\n\n\n\n\nfunction handleAction_SALE_DATA_SNAPSHOT_INIT(state:ReduxWebcastCurrentRoundBiddingType, payload:PMAuctionDataSnapshot):ReduxWebcastCurrentRoundBiddingType {\n const payloadCurrentRound:Round = payload.currentRound;\n\n if (payloadCurrentRound) {\n const bidsHistory = transformApiBidsHistory(payloadCurrentRound.bidsHistory);\n const highestBid = bidsHistory && bidsHistory.length ? bidsHistory[bidsHistory.length - 1] : null;\n const choiceLotsSelection = [];\n\n let choiceSubmitted = false;\n if (payload.choiceLotsIds && payload.choiceLotsIds.length) {\n payload.choiceLotsIds.forEach((payloadLotId, idx) => {\n const payloadUserId = payload.choiceUsersIds[idx];\n choiceLotsSelection.push([payloadLotId, payloadUserId]);\n if (payloadUserId === state.myUserId) {\n choiceSubmitted = true;\n }\n });\n }\n\n\n return {\n ... state,\n ... computeHighestOnlineBidsSubState(payloadCurrentRound),\n roundId: payloadCurrentRound.roundId,\n askingBidValue: payload.askingBidValue,\n bidIncrement: payload.bidIncrement,\n bidsHistory: bidsHistory,\n highestBid: highestBid,\n choiceLotsSelection: choiceLotsSelection,\n choiceLotsSelectionMap: new Map(choiceLotsSelection),\n choiceSelectionSubmitted: choiceSubmitted,\n }\n }\n\n return state;\n}\n\n\n\n\n\n\n\nfunction handleAction_CURRENT_ROUND_BIDDING_UPDATE(state:ReduxWebcastCurrentRoundBiddingType, payload:PMBiddingUpdated):ReduxWebcastCurrentRoundBiddingType {\n\n\n // first priority, we check if this is a bidRevise\n if (payload.bidReviseType && payload.bidReviseType !== 0) {\n // bid reverse or override\n const existingBiddingHistory = state.bidsHistory || [];\n if (existingBiddingHistory.length === 0) {\n alert('FATAL ERROR [rcb268]: BidRevise triggered with no bids history. Please reload page and report this issue!');\n throw 'FATAL ERROR: BidRevise triggered with no bids history. Please reload page and report this issue!';\n }\n\n if (payload.bidReviseType === BidReviseTypeEnum.OVERRIDE_BY_FLOOR) {\n const lastBid = existingBiddingHistory[existingBiddingHistory.length - 1];\n\n const overriddenBid:Bid = {\n ... lastBid,\n overridden: true\n };\n\n const newFloorBid:Bid = decorateBid(payload.bidsPlaced[0]);\n\n // new history must replace the last bid and and re-add it as overridden, then add the floor bid last\n const newBiddingHistory = [ ... existingBiddingHistory.slice(0, existingBiddingHistory.length - 1), overriddenBid, newFloorBid ];\n\n return {\n ... state,\n\n askingBidValue: payload.askingBidValue,\n bidIncrement: payload.bidIncrement,\n\n highestBid: newFloorBid,\n bidsHistory: newBiddingHistory,\n }\n }\n else { // reverse\n\n // the newHighestBid that should remain in the history is the only bid in the payload.BidsPlaced\n const payloadNewHighestBid:Bid = payload.bidsPlaced[0];\n\n let newBidsHistory:Array;\n\n if (payloadNewHighestBid) {\n // remove all bids to match new highest remaining bid\n newBidsHistory = existingBiddingHistory.filter((bid:Bid) => {\n return bid.timestamp <= payloadNewHighestBid.timestamp;\n });\n }\n else {\n // no newHighestBid => no bids history left\n newBidsHistory = null;\n }\n\n let newHighestBid:Bid = (newBidsHistory && newBidsHistory.length) ? newBidsHistory[newBidsHistory.length - 1] : null;\n if (newHighestBid && newHighestBid.overridden && newBidsHistory) {\n // remove override from the new highestBid\n newHighestBid = {\n ... newHighestBid,\n overridden: false,\n };\n\n // remove the old \"newBiddingHistory\" and add the new \"newBiddingHistory\" that doesn't have `overridden`\n newBidsHistory = [ ... newBidsHistory.slice(0, newBidsHistory.length -1 ), newHighestBid ];\n }\n\n\n return {\n ... state,\n\n askingBidValue: payload.askingBidValue,\n bidIncrement: payload.bidIncrement,\n\n highestBid: newHighestBid,\n\n bidsHistory: newBidsHistory,\n }\n }\n }\n else if (payload.bidsPlaced && payload.bidsPlaced.length) {\n\n\n let highestBid:Bid = null;\n const newExtraBidsHistory:Array = [];\n\n [... payload.bidsPlaced].reverse().forEach((placedBid:Bid) => {\n highestBid = decorateBid(placedBid);\n newExtraBidsHistory.push(highestBid);\n });\n\n\n // a bid has been placed\n const existingBiddingHistory = state.bidsHistory || [];\n\n return {\n ... state,\n\n roundId: payload.roundId,\n\n askingBidValue: payload.askingBidValue,\n bidIncrement: payload.bidIncrement,\n\n highestBid: highestBid,\n\n bidsHistory: [... existingBiddingHistory, ... newExtraBidsHistory],\n }\n }\n else {\n // the askingBid was updated, and maybe there also a new increment\n return {\n ... state,\n ... initialResetState,\n\n roundId: payload.roundId,\n\n askingBidValue: payload.askingBidValue,\n bidIncrement: payload.bidIncrement,\n\n highestBid: state.highestBid,\n\n bidsHistory: state.bidsHistory,\n\n // save some state info from before\n firstOnlineBid: state.firstOnlineBid,\n secondOnlineBid: state.secondOnlineBid,\n }\n }\n}\n", "import {Participant, PMParticipantsUpdated, PMAuctionDataSnapshot, Round} from \"../../data/data_types_definitions\";\nimport { ActionsCreators } from \"../actions\";\nimport {createReducer} from \"@reduxjs/toolkit\";\n\n\nexport type ReduxWebcastParticipantsType = {\n mapByUserId: Map,\n onlineBidders: Array,\n offlineBidders: Array,\n onlineViewers: Array,\n offlineViewers: Array,\n};\n\n\n\nconst initialState:ReduxWebcastParticipantsType = {\n mapByUserId: new Map(),\n onlineBidders: [],\n offlineBidders: [],\n onlineViewers: [],\n offlineViewers: []\n};\n\n\n\nconst _participantsByUserId = new Map();\n\n\n\n/**\n * combined as `webcastParticipants`\n *\n * ===\n * action: WEBCAST_AUCTION_DATA_SNAPSHOT_INIT\n * payload: {\n * participants: Array,\n * }\n *\n *\n * ===\n * action: WEBCAST_CLERK_PARTICIPANTS_UPDATE\n * payload: <> {\n * online?: Array,\n * offline?: Array\n * }\n *\n *\n *\n * @param state\n * @param action\n * @returns {{\n * mapByUserId: Map,\n * onlineBidders: [],\n * offlineBidders: [],\n * onlineViewers: [],\n * offlineViewers: []\n * }}\n */\n\nconst reducerWebcastParticipants = createReducer(initialState, (builder) => {\n\n builder.addCase(ActionsCreators.webcast.webcastAuctionInit, (state, action) => {\n state.mapByUserId = initialState.mapByUserId;\n state.onlineBidders = initialState.onlineBidders;\n state.offlineBidders = initialState.offlineBidders;\n state.onlineViewers = initialState.onlineViewers;\n state.offlineViewers= initialState.offlineViewers;\n });\n\n\n\n builder.addCase(ActionsCreators.webcast.webcastAuctionDataSnapshotInit, (state, action) => {\n const payload: PMAuctionDataSnapshot = action.payload;\n const participants = payload && payload.participants;\n\n if (participants) {\n participants.forEach(p => _participantsByUserId.set(p.userId, p));\n }\n\n _createStateFromParticipantsMap(state);\n\n });\n\n builder.addCase(ActionsCreators.webcast.webcastClerkParticipantsUpdate, (state, action) => {\n const payload:PMParticipantsUpdated = action.payload\n if (payload) {\n if (payload.online && payload.online.length) {\n payload.online.forEach((p) => {\n _participantsByUserId.set(p.userId, p); // just overwrite the Map entry; p.connectedWS should be `true` !\n })\n }\n if (payload.offline && payload.offline.length) {\n payload.offline.forEach(userId => {\n const existingParticipant = _participantsByUserId.get(userId);\n if (existingParticipant) {\n _participantsByUserId.set(userId, {...existingParticipant, connected: false});\n }\n });\n }\n _createStateFromParticipantsMap(state);\n }\n });\n\n});\n\n\nfunction _createStateFromParticipantsMap(state) {\n const onlineBidders = [];\n const offlineBidders = [];\n const onlineViewers = [];\n const offlineViewers = [];\n const mapByUserId = new Map();\n\n\n _participantsByUserId.forEach((p, userId) => {\n\n mapByUserId.set(userId, decorateParticipant(p));\n\n if (p.connected) {\n if (p.userRole === 'bidder') {\n onlineBidders.push(p);\n }\n else if (p.userRole === 'viewer') {\n onlineViewers.push(p);\n }\n }\n else {\n if (p.userRole === 'bidder') {\n offlineBidders.push(p);\n }\n else if (p.userRole === 'viewer') {\n offlineViewers.push(p);\n }\n }\n });\n\n state.mapByUserId = mapByUserId;\n state.onlineBidders = onlineBidders;\n state.offlineBidders = offlineBidders;\n state.onlineViewers = onlineViewers;\n state.offlineViewers = offlineViewers;\n}\n\n\n\nfunction decorateParticipant(participant:Participant):Participant {\n return {\n ... participant,\n bidderDisplay: computeBidderDisplay(participant),\n }\n}\n\n\nfunction computeBidderDisplay(participant:Participant):string {\n if (participant.bidderNo === '0' ) {\n return 'FLOOR';\n }\n else if (participant.bidderLabel && participant.bidderLabel.length) {\n return `${participant.bidderNo} (${participant.bidderLabel})`;\n }\n else {\n return participant.bidderNo\n }\n}\n\nexport default reducerWebcastParticipants;\n", "import { ActionsCreators } from \"../actions\";\nimport {ChatMessage, ChatRoom, PMAuctionDataSnapshot} from \"../../data/data_types_definitions\";\nimport {WebcastAuctionConnectData_TypeDef} from \"../../services/AuctionsManager\";\nimport {createReducer} from \"@reduxjs/toolkit\";\n\nexport type ReduxWebcastChatType = {\n myUserInfo: { userId: number, userRole: string, userRoleIsClerk: boolean, senderUserId:number },\n chatRooms: Array,\n chatRoomsById: Map,\n activeChatRoomId: number,\n};\n\n\nconst initialState: ReduxWebcastChatType = {\n myUserInfo: null,\n chatRooms: [],\n chatRoomsById: new Map(),\n activeChatRoomId: null,\n};\n\n\n\n\n/**\n * combined as `webcastChat`\n *\n * ===\n * action: WEBCAST_AUCTION_INIT\n * payload: {\n * participantId: number,\n * userRole: string\n * }\n *\n *\n * ===\n * action: WEBCAST_AUCTION_DATA_SNAPSHOT_INIT\n * payload: {\n * chatRooms: Array, // for Bidder, this array will have at most one element\n * }\n *\n *\n * ===\n * action: WEBCAST_CHAT_MESSAGE_POST\n * payload: {\n * roomId: number,\n * sender: number,\n * timestamp: number,\n * body: string\n * }\n *\n *\n *\n * ===\n * action: WEBCAST_CHAT_ROOM_OPEN_AND_READ\n * payload: {\n * roomId: number\n * }\n *\n *\n * ==\n * action: WEBCAST_CHAT_ROOM_CLOSE\n * payload: {\n * roomId: number\n * }\n *\n *\n *\n *\n * @param state\n * @param action\n * @returns {{\n * myUserInfo: { participantId: number, userRole: string, userRoleIsClerk: boolean, senderUserId: number },\n * chatRooms: Array,\n * chatRoomsById: Map\n * activeChatRoomId: number,\n * }}\n */\n\n\nconst reducerWebcastChat = createReducer(initialState, (builder) => {\n builder.addCase(ActionsCreators.webcast.webcastAuctionInit, (state, action) => {\n const saleConnectData:WebcastAuctionConnectData_TypeDef = action.payload;\n const userIsClerk = saleConnectData.participantRole === 'clerk';\n\n state.chatRoomsById = initialState.chatRoomsById;\n state.chatRooms = initialState.chatRooms;\n state.activeChatRoomId = initialState.activeChatRoomId;\n\n state.myUserInfo = {\n userId: saleConnectData.participantId,\n userRole: saleConnectData.participantRole,\n userRoleIsClerk: userIsClerk,\n senderUserId: userIsClerk ? 0 : saleConnectData.participantId,\n }\n });\n\n builder.addCase(ActionsCreators.webcast.webcastAuctionDataSnapshotInit, (state, action) => {\n const payload: PMAuctionDataSnapshot = action.payload;\n const myUserInfo = state.myUserInfo;\n const payloadChatRoomsMap:Map = new Map(payload.chatRooms.map(r => [r.id, r]));\n const chatRooms:Array = [];\n\n // all users have the BROADCAST chatroom (although bidders can only read and cannot send to it)\n const payloadBroadcastChatRoom:ChatRoom = payloadChatRoomsMap.get(-1) || { messages: null };\n\n const broadcastChatRoom:ChatRoom = {\n id: -1,\n messages: payloadBroadcastChatRoom.messages || [],\n lastReadTimestamp: 0,\n unreadCount: 0,\n };\n\n chatRooms.push(broadcastChatRoom);\n\n // process with all the other received (payload) ChatRooms\n payloadChatRoomsMap.forEach((payloadChatRoom:ChatRoom) => {\n\n // skip the special chatrooms we processed already\n if (payloadChatRoom.id === 0 || payloadChatRoom.id === -1) {\n return;\n }\n\n // each non special chat-room gets the broadcast messages included\n const roomMessages:Array = [].concat(payloadChatRoom.messages || [], broadcastChatRoom.messages);\n\n // sort ascending by timestamp\n roomMessages.sort((m1:ChatMessage, m2:ChatMessage) => {\n return m1.timestamp - m2.timestamp;\n });\n\n\n chatRooms.push({\n id: payloadChatRoom.id,\n messages: roomMessages,\n lastReadTimestamp: 0,\n unreadCount: 0,\n });\n\n });\n\n\n if (myUserInfo.userRoleIsClerk) {\n // for the Clerk user, we need to add the \"special\" ADMIN chatroom\n\n const payloadAdminsChatRoom: ChatRoom = payloadChatRoomsMap.get(0) || { messages: null };\n\n // the \"ADMINS\" room\n\n chatRooms.push({\n id: 0,\n messages: payloadAdminsChatRoom.messages || [],\n lastReadTimestamp: 0,\n unreadCount: 0,\n });\n }\n else if ( ! payloadChatRoomsMap.get(myUserInfo.userId)) {\n // ensure own ChatRoom exists, and create empty if not\n chatRooms.push({\n id: myUserInfo.userId,\n messages: [],\n lastReadTimestamp: 0,\n unreadCount: 0,\n })\n }\n\n chatRooms.sort(chatRoomsSortFunc);\n\n state.chatRooms = chatRooms;\n state.chatRoomsById = new Map(chatRooms.map((r) => [r.id, r]));\n });\n\n\n\n builder.addCase(ActionsCreators.webcast.webcastChatMessagePost, (state, action) => {\n const chatMessage:ChatMessage = action.payload;\n\n let updatedChatRooms:Array;\n\n if (chatMessage.roomId === -1) {\n // BROADCAST\n\n // update all chat rooms, including the \"BROADCAST\" room (id= -1)\n updatedChatRooms = state.chatRooms.map((chatRoom) => {\n if (chatRoom.id === 0) {\n // skip adding the message updates for the ADMIN chat room\n return chatRoom;\n }\n\n const newChatMessages = [...chatRoom.messages, chatMessage];\n\n // if \"my user is clerk\", then don't update the unread count\n if (state.myUserInfo.userRoleIsClerk) {\n\n // TODO\n return {\n ...chatRoom,\n messages: newChatMessages,\n };\n }\n\n // for a bidder, update the unreadCount\n let newUnreadCount;\n if (chatMessage.sender === state.myUserInfo.userId) {\n // if sent by \"myself\", then reset to 0\n newUnreadCount = 0;\n }\n else {\n // if sent by \"the other guy\", then increase\n newUnreadCount = (chatRoom.unreadCount || 0) + 1;\n }\n\n // TODO\n return {\n ...chatRoom,\n messages: newChatMessages,\n unreadCount: newUnreadCount,\n }\n });\n\n state.chatRooms = updatedChatRooms;\n state.chatRoomsById = new Map(updatedChatRooms.map((r) => [r.id, r]));\n\n }\n else {\n // non-broadcast, message sent to room by participant (sender can be either: room-owner (i.e. bidder/viewer) or clerk)\n let chatRoom:ChatRoom = state.chatRoomsById.get(chatMessage.roomId);\n\n if (chatRoom) {\n // if chatRoom exists already in the list, then just change its object reference\n chatRoom = { ... chatRoom };\n\n // and replace it in the list\n updatedChatRooms = state.chatRooms.map((cr) => {\n return (cr.id === chatMessage.roomId) ? chatRoom : cr;\n })\n }\n else {\n chatRoom = {\n id: chatMessage.roomId,\n messages: [],\n lastReadTimestamp: 0,\n unreadCount: 0,\n };\n\n updatedChatRooms = [ chatRoom, ...state.chatRooms ];\n }\n\n\n\n if (chatMessage.sender === state.myUserInfo.senderUserId) {\n // sender is \"myself\" => reset unreadCount\n chatRoom.lastReadTimestamp = Date.now();\n chatRoom.unreadCount = 0;\n }\n else {\n // sender is \"the other guy\" => increase unreadCount\n chatRoom.unreadCount = (chatRoom.unreadCount || 0) + 1;\n }\n\n\n // update the chatRoom with the new message and unreadCount, keep object identity here\n chatRoom.isClosed = false; // re-open to show in the Clerk's list\n chatRoom.messages = [ ...chatRoom.messages, chatMessage ];\n\n\n updatedChatRooms.sort(chatRoomsSortFunc);\n\n state.chatRooms = updatedChatRooms;\n state.chatRoomsById = new Map(updatedChatRooms.map((r) => [r.id, r]));\n\n }\n });\n\n\n\n builder.addCase(ActionsCreators.webcast.webcastChatRoomOpenAndMarkAsRead, (state, action) => {\n\n const roomId:number = action.payload;\n\n let newChatRoom:ChatRoom = null;\n\n\n const updatedChatRooms = state.chatRooms.map((chatRoom:ChatRoom) => {\n if (chatRoom.id !== roomId) {\n return chatRoom;\n }\n else {\n newChatRoom = {\n ... chatRoom,\n isClosed: false,\n unreadCount: 0,\n lastReadTimestamp: Date.now(), // in milliseconds\n };\n return newChatRoom\n }\n });\n\n\n\n\n if (! newChatRoom) {\n newChatRoom = {\n id: roomId,\n messages: [],\n unreadCount: 0,\n lastReadTimestamp: Date.now(), // in milliseconds\n };\n\n updatedChatRooms.push(newChatRoom);\n }\n\n updatedChatRooms.sort(chatRoomsSortFunc);\n\n state.activeChatRoomId = newChatRoom.id;\n state.chatRooms = updatedChatRooms;\n state.chatRoomsById = new Map(updatedChatRooms.map((r) => [r.id, r]));\n });\n\n builder.addCase(ActionsCreators.webcast.webcastChatRoomClose, (state, action) => {\n const roomId:number = action.payload;\n\n const updatedChatRooms = state.chatRooms.map((chatRoom:ChatRoom) => {\n if (chatRoom.id === roomId) {\n return {\n ... chatRoom,\n unreadCount: 0,\n isClosed: true,\n }\n }\n return chatRoom;\n });\n\n state.activeChatRoomId = null;\n state.chatRooms = updatedChatRooms;\n state.chatRoomsById = new Map(updatedChatRooms.map((r) => [r.id, r]));\n });\n\n});\n\n\n\n\n\n\nfunction chatRoomsSortFunc(r1:ChatRoom, r2:ChatRoom) {\n // to sort descending, r1 needs to return smaller number\n\n if (r1.id === -1 || r2.id === -1) {\n // the 'ALL' (BROADCAST) room is always 1st\n return r1.id === -1 ? Number.MIN_SAFE_INTEGER : Number.MAX_SAFE_INTEGER;\n }\n else if (r1.id === 0 || r2.id === 0) {\n // the 'ADMIN' room is always 2nd\n return r1.id === 0 ? Number.MIN_SAFE_INTEGER + 1 : Number.MAX_SAFE_INTEGER - 1;\n }\n else {\n // if both have unreadCount ...\n if (r1.unreadCount > 0 && r2.unreadCount > 0) {\n // sort by lastReadTimestamp descending\n return (r1.lastReadTimestamp > r2.lastReadTimestamp) ? -20000000000 : 20000000000;\n }\n // if both don't have unread ...\n else if (r1.unreadCount === 0 && r2.unreadCount === 0) {\n // sort by roomId descending\n const r1id = r1.id < 0 ? Math.abs(r1.id) * 10000000000 : r1.id;\n const r2id = r2.id < 0 ? Math.abs(r2.id) * 10000000000 : r2.id;\n return (r1id > r2id) ? 1 : -1;\n }\n else {\n // only one has unread count > 0, goes at the top\n return r1.unreadCount > 0 ? -20000000000 : 20000000000;\n }\n }\n}\n\nexport default reducerWebcastChat;\n", "import reducerWbsNetworkStatus, {ReduxWebcastWbsNetworkStatusType} from \"./webcast/reducerWbsNetworkStatus\";\nimport reducerWebcastStatus, {ReduxWebcastStatusType} from \"./webcast/reducerWebcastStatus\";\nimport reducerWebcastAuctionData, {ReduxWebcastAuctionDataType} from \"./webcast/reducerWebcastAuctionData\";\nimport reducerWebcastCurrentRound, {ReduxWebcastCurrentRoundType} from \"./webcast/reducerWebcastCurrentRound\";\nimport reducerWebcastCurrentRoundBidding, {ReduxWebcastCurrentRoundBiddingType} from \"./webcast/reducerWebcastCurrentRoundBidding\";\nimport reducerWebcastParticipants, {ReduxWebcastParticipantsType} from \"./webcast/reducerWebcastParticipants\";\nimport reducerWebcastChat, {ReduxWebcastChatType} from \"./webcast/reducerWebcastChat\";\nimport {combineReducers} from \"@reduxjs/toolkit\";\n\n\nexport type ReduxActiveWebcastSubStateType = {\n\n wbsNetworkStatus: ReduxWebcastWbsNetworkStatusType,\n\n webcastStatus?: ReduxWebcastStatusType,\n\n webcastAuctionData: ReduxWebcastAuctionDataType,\n\n webcastCurrentRound?: ReduxWebcastCurrentRoundType,\n\n webcastCurrentRoundBidding?: ReduxWebcastCurrentRoundBiddingType,\n\n\n webcastChat?: ReduxWebcastChatType,\n\n\n webcastParticipants?: ReduxWebcastParticipantsType,\n};\n\n\n\n/**\n * combined as `activeWebcast`\n */\nconst activeWebcastRootState = {\n\n wbsNetworkStatus: reducerWbsNetworkStatus,\n\n webcastStatus: reducerWebcastStatus,\n\n webcastAuctionData: reducerWebcastAuctionData,\n webcastCurrentRound: reducerWebcastCurrentRound,\n webcastCurrentRoundBidding: reducerWebcastCurrentRoundBidding,\n\n webcastChat: reducerWebcastChat,\n\n // clerk only\n webcastParticipants: reducerWebcastParticipants,\n};\n\n\nexport default combineReducers(activeWebcastRootState);\n", "import {Store} from \"redux\";\nimport {combineReducers, configureStore} from \"@reduxjs/toolkit\";\nimport reducerActiveWebcast from \"../redux/reducerActiveWebcast\";\nimport {NextLotJSDATA_TypeDef} from \"../../NextLotJSDATA\";\n\nconst rootReducer = combineReducers({\n activeWebcast: reducerActiveWebcast,\n});\n\n\nconst reduxStore = configureStore({\n\n reducer: rootReducer,\n\n devTools: __DEV__\n ? {\n serialize: {\n options: true\n }\n }\n : false,\n\n middleware: (getDefaultMiddleware) =>\n getDefaultMiddleware({\n serializableCheck: {\n // Ignore these action types\n // ignoredActions: ['your/action/type'],\n // Ignore these field paths in all actions\n ignoredActionPaths: ['meta.arg', 'payload.timestamp'],\n // Ignore these paths in the state\n ignoredPaths: ['activeWebcast'],\n },\n }),\n});\n\n\n\nlet _configBucket = null;\n\n\nexport type ReduxStateType = ReturnType;\nexport type AppDispatchType = typeof reduxStore.dispatch;\n\n\nexport default class DataStore {\n\n static init(configData:NextLotJSDATA_TypeDef) {\n _configBucket = Object.freeze({\n ... configData\n });\n }\n\n\n static get reduxStore():Store {\n return reduxStore;\n }\n\n static get config():NextLotJSDATA_TypeDef {\n return _configBucket;\n }\n}\n\n", "/*\n currency.js - v2.0.4\n http://scurker.github.io/currency.js\n\n Copyright (c) 2021 Jason Wilson\n Released under MIT license\n*/\n(function(e,g){\"object\"===typeof exports&&\"undefined\"!==typeof module?module.exports=g():\"function\"===typeof define&&define.amd?define(g):(e=e||self,e.currency=g())})(this,function(){function e(b,a){if(!(this instanceof e))return new e(b,a);a=Object.assign({},m,a);var d=Math.pow(10,a.precision);this.intValue=b=g(b,a);this.value=b/d;a.increment=a.increment||1/d;a.groups=a.useVedic?n:p;this.s=a;this.p=d}function g(b,a){var d=2;\n\nconst THRESHOLD_DOLLAR_AMOUNT_SHOW_DECIMALS = 10;\n\nconst groupRegex = /(\\d)(?=(\\d{3})+\\b)/g;\n\n\nconst CURRENCY_OPTIONS:{[Key:string]:CurrencyOptions_TypeDef} = {\n 'USD': { symbol: \"$\", separator: \",\", decimal: \".\", precision: 2 },\n 'CAD': { symbol: \"$\", separator: \",\", decimal: \".\", precision: 2 },\n 'AUD': { symbol: \"$\", separator: \",\", decimal: \".\", precision: 2 },\n 'EUR': { symbol: \"\u20AC\", separator: \",\", decimal: \".\", precision: 2 },\n 'GBP': { symbol: \"\u00A3\", separator: \",\", decimal: \".\", precision: 2 },\n}\n\nfunction formatFunc(currency: currency, opts: Options):string {\n // console.log('>>>>[formatFunc]>>>>', currency, opts);\n\n const currencySymbolPrefix:string = opts.symbol;\n const dollars:number = currency.dollars();\n const cents:number = currency.cents() // result can be between 0 and 99\n\n let centsStr:string|null = null;\n if (cents > 0) {\n centsStr = '.' + String(cents).padStart(2, '0');\n }\n // else if (dollars < THRESHOLD_DOLLAR_AMOUNT_SHOW_DECIMALS) { // and cents == 0\n // centsStr = '.00';\n // }\n\n // Handle correction for currency values greater than `2 ** 31` (2_147_483_648) when the `~~` bitwiseNOT operator overflows.\n // https://stackoverflow.com/a/75849951\n const dollarCorrection = currency.value > 2_147_483_648 ? Math.trunc(currency.value) : dollars;\n const dollarsStr = String(dollarCorrection).replace(groupRegex, '$1' + opts.separator);\n\n return `${currencySymbolPrefix}${dollarsStr}${centsStr ? centsStr : ''}`;\n}\n\n\nclass MoneyHelper {\n private readonly currencyOptions:CurrencyOptions_TypeDef & Options;\n\n constructor(currencyCode:string) {\n this.currencyOptions = {\n ... CURRENCY_OPTIONS[currencyCode],\n format: formatFunc,\n }\n }\n\n fromCents = (amountCents) => (currency(amountCents, { ... this.currencyOptions, fromCents: true }));\n fromAmount = (amount) => (currency(amount, { ... this.currencyOptions}));\n\n formatFromCents = (amountCents) => (this.fromCents(amountCents).format());\n amountFromCents = (amountCents) => (this.fromCents(amountCents).value);\n\n}\n\n\nconst MONEY_HELPERS_MAP_BY_CURRENCY_CODE:Map = new Map(\n Object.keys(CURRENCY_OPTIONS)\n .map((currencyCode) => {\n return [currencyCode, new MoneyHelper(currencyCode)];\n }));\n\n\nexport function getMoneyHelperForCurrencyCode(currencyCode:string = 'USD'):MoneyHelper {\n return MONEY_HELPERS_MAP_BY_CURRENCY_CODE.get(currencyCode);\n}\n", "'use strict';\n\nexport default function bind(fn, thisArg) {\n return function wrap() {\n return fn.apply(thisArg, arguments);\n };\n}\n", "'use strict';\n\nimport bind from './helpers/bind.js';\n\n// utils is a library of generic helper functions non-specific to axios\n\nconst {toString} = Object.prototype;\nconst {getPrototypeOf} = Object;\n\nconst kindOf = (cache => thing => {\n const str = toString.call(thing);\n return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());\n})(Object.create(null));\n\nconst kindOfTest = (type) => {\n type = type.toLowerCase();\n return (thing) => kindOf(thing) === type\n}\n\nconst typeOfTest = type => thing => typeof thing === type;\n\n/**\n * Determine if a value is an Array\n *\n * @param {Object} val The value to test\n *\n * @returns {boolean} True if value is an Array, otherwise false\n */\nconst {isArray} = Array;\n\n/**\n * Determine if a value is undefined\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if the value is undefined, otherwise false\n */\nconst isUndefined = typeOfTest('undefined');\n\n/**\n * Determine if a value is a Buffer\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a Buffer, otherwise false\n */\nfunction isBuffer(val) {\n return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)\n && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val);\n}\n\n/**\n * Determine if a value is an ArrayBuffer\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is an ArrayBuffer, otherwise false\n */\nconst isArrayBuffer = kindOfTest('ArrayBuffer');\n\n\n/**\n * Determine if a value is a view on an ArrayBuffer\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false\n */\nfunction isArrayBufferView(val) {\n let result;\n if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {\n result = ArrayBuffer.isView(val);\n } else {\n result = (val) && (val.buffer) && (isArrayBuffer(val.buffer));\n }\n return result;\n}\n\n/**\n * Determine if a value is a String\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a String, otherwise false\n */\nconst isString = typeOfTest('string');\n\n/**\n * Determine if a value is a Function\n *\n * @param {*} val The value to test\n * @returns {boolean} True if value is a Function, otherwise false\n */\nconst isFunction = typeOfTest('function');\n\n/**\n * Determine if a value is a Number\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a Number, otherwise false\n */\nconst isNumber = typeOfTest('number');\n\n/**\n * Determine if a value is an Object\n *\n * @param {*} thing The value to test\n *\n * @returns {boolean} True if value is an Object, otherwise false\n */\nconst isObject = (thing) => thing !== null && typeof thing === 'object';\n\n/**\n * Determine if a value is a Boolean\n *\n * @param {*} thing The value to test\n * @returns {boolean} True if value is a Boolean, otherwise false\n */\nconst isBoolean = thing => thing === true || thing === false;\n\n/**\n * Determine if a value is a plain Object\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a plain Object, otherwise false\n */\nconst isPlainObject = (val) => {\n if (kindOf(val) !== 'object') {\n return false;\n }\n\n const prototype = getPrototypeOf(val);\n return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val);\n}\n\n/**\n * Determine if a value is a Date\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a Date, otherwise false\n */\nconst isDate = kindOfTest('Date');\n\n/**\n * Determine if a value is a File\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a File, otherwise false\n */\nconst isFile = kindOfTest('File');\n\n/**\n * Determine if a value is a Blob\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a Blob, otherwise false\n */\nconst isBlob = kindOfTest('Blob');\n\n/**\n * Determine if a value is a FileList\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a File, otherwise false\n */\nconst isFileList = kindOfTest('FileList');\n\n/**\n * Determine if a value is a Stream\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a Stream, otherwise false\n */\nconst isStream = (val) => isObject(val) && isFunction(val.pipe);\n\n/**\n * Determine if a value is a FormData\n *\n * @param {*} thing The value to test\n *\n * @returns {boolean} True if value is an FormData, otherwise false\n */\nconst isFormData = (thing) => {\n let kind;\n return thing && (\n (typeof FormData === 'function' && thing instanceof FormData) || (\n isFunction(thing.append) && (\n (kind = kindOf(thing)) === 'formdata' ||\n // detect form-data instance\n (kind === 'object' && isFunction(thing.toString) && thing.toString() === '[object FormData]')\n )\n )\n )\n}\n\n/**\n * Determine if a value is a URLSearchParams object\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a URLSearchParams object, otherwise false\n */\nconst isURLSearchParams = kindOfTest('URLSearchParams');\n\nconst [isReadableStream, isRequest, isResponse, isHeaders] = ['ReadableStream', 'Request', 'Response', 'Headers'].map(kindOfTest);\n\n/**\n * Trim excess whitespace off the beginning and end of a string\n *\n * @param {String} str The String to trim\n *\n * @returns {String} The String freed of excess whitespace\n */\nconst trim = (str) => str.trim ?\n str.trim() : str.replace(/^[\\s\\uFEFF\\xA0]+|[\\s\\uFEFF\\xA0]+$/g, '');\n\n/**\n * Iterate over an Array or an Object invoking a function for each item.\n *\n * If `obj` is an Array callback will be called passing\n * the value, index, and complete array for each item.\n *\n * If 'obj' is an Object callback will be called passing\n * the value, key, and complete object for each property.\n *\n * @param {Object|Array} obj The object to iterate\n * @param {Function} fn The callback to invoke for each item\n *\n * @param {Boolean} [allOwnKeys = false]\n * @returns {any}\n */\nfunction forEach(obj, fn, {allOwnKeys = false} = {}) {\n // Don't bother if no value provided\n if (obj === null || typeof obj === 'undefined') {\n return;\n }\n\n let i;\n let l;\n\n // Force an array if not already something iterable\n if (typeof obj !== 'object') {\n /*eslint no-param-reassign:0*/\n obj = [obj];\n }\n\n if (isArray(obj)) {\n // Iterate over array values\n for (i = 0, l = obj.length; i < l; i++) {\n fn.call(null, obj[i], i, obj);\n }\n } else {\n // Iterate over object keys\n const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);\n const len = keys.length;\n let key;\n\n for (i = 0; i < len; i++) {\n key = keys[i];\n fn.call(null, obj[key], key, obj);\n }\n }\n}\n\nfunction findKey(obj, key) {\n key = key.toLowerCase();\n const keys = Object.keys(obj);\n let i = keys.length;\n let _key;\n while (i-- > 0) {\n _key = keys[i];\n if (key === _key.toLowerCase()) {\n return _key;\n }\n }\n return null;\n}\n\nconst _global = (() => {\n /*eslint no-undef:0*/\n if (typeof globalThis !== \"undefined\") return globalThis;\n return typeof self !== \"undefined\" ? self : (typeof window !== 'undefined' ? window : global)\n})();\n\nconst isContextDefined = (context) => !isUndefined(context) && context !== _global;\n\n/**\n * Accepts varargs expecting each argument to be an object, then\n * immutably merges the properties of each object and returns result.\n *\n * When multiple objects contain the same key the later object in\n * the arguments list will take precedence.\n *\n * Example:\n *\n * ```js\n * var result = merge({foo: 123}, {foo: 456});\n * console.log(result.foo); // outputs 456\n * ```\n *\n * @param {Object} obj1 Object to merge\n *\n * @returns {Object} Result of all merge properties\n */\nfunction merge(/* obj1, obj2, obj3, ... */) {\n const {caseless} = isContextDefined(this) && this || {};\n const result = {};\n const assignValue = (val, key) => {\n const targetKey = caseless && findKey(result, key) || key;\n if (isPlainObject(result[targetKey]) && isPlainObject(val)) {\n result[targetKey] = merge(result[targetKey], val);\n } else if (isPlainObject(val)) {\n result[targetKey] = merge({}, val);\n } else if (isArray(val)) {\n result[targetKey] = val.slice();\n } else {\n result[targetKey] = val;\n }\n }\n\n for (let i = 0, l = arguments.length; i < l; i++) {\n arguments[i] && forEach(arguments[i], assignValue);\n }\n return result;\n}\n\n/**\n * Extends object a by mutably adding to it the properties of object b.\n *\n * @param {Object} a The object to be extended\n * @param {Object} b The object to copy properties from\n * @param {Object} thisArg The object to bind function to\n *\n * @param {Boolean} [allOwnKeys]\n * @returns {Object} The resulting value of object a\n */\nconst extend = (a, b, thisArg, {allOwnKeys}= {}) => {\n forEach(b, (val, key) => {\n if (thisArg && isFunction(val)) {\n a[key] = bind(val, thisArg);\n } else {\n a[key] = val;\n }\n }, {allOwnKeys});\n return a;\n}\n\n/**\n * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)\n *\n * @param {string} content with BOM\n *\n * @returns {string} content value without BOM\n */\nconst stripBOM = (content) => {\n if (content.charCodeAt(0) === 0xFEFF) {\n content = content.slice(1);\n }\n return content;\n}\n\n/**\n * Inherit the prototype methods from one constructor into another\n * @param {function} constructor\n * @param {function} superConstructor\n * @param {object} [props]\n * @param {object} [descriptors]\n *\n * @returns {void}\n */\nconst inherits = (constructor, superConstructor, props, descriptors) => {\n constructor.prototype = Object.create(superConstructor.prototype, descriptors);\n constructor.prototype.constructor = constructor;\n Object.defineProperty(constructor, 'super', {\n value: superConstructor.prototype\n });\n props && Object.assign(constructor.prototype, props);\n}\n\n/**\n * Resolve object with deep prototype chain to a flat object\n * @param {Object} sourceObj source object\n * @param {Object} [destObj]\n * @param {Function|Boolean} [filter]\n * @param {Function} [propFilter]\n *\n * @returns {Object}\n */\nconst toFlatObject = (sourceObj, destObj, filter, propFilter) => {\n let props;\n let i;\n let prop;\n const merged = {};\n\n destObj = destObj || {};\n // eslint-disable-next-line no-eq-null,eqeqeq\n if (sourceObj == null) return destObj;\n\n do {\n props = Object.getOwnPropertyNames(sourceObj);\n i = props.length;\n while (i-- > 0) {\n prop = props[i];\n if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {\n destObj[prop] = sourceObj[prop];\n merged[prop] = true;\n }\n }\n sourceObj = filter !== false && getPrototypeOf(sourceObj);\n } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);\n\n return destObj;\n}\n\n/**\n * Determines whether a string ends with the characters of a specified string\n *\n * @param {String} str\n * @param {String} searchString\n * @param {Number} [position= 0]\n *\n * @returns {boolean}\n */\nconst endsWith = (str, searchString, position) => {\n str = String(str);\n if (position === undefined || position > str.length) {\n position = str.length;\n }\n position -= searchString.length;\n const lastIndex = str.indexOf(searchString, position);\n return lastIndex !== -1 && lastIndex === position;\n}\n\n\n/**\n * Returns new array from array like object or null if failed\n *\n * @param {*} [thing]\n *\n * @returns {?Array}\n */\nconst toArray = (thing) => {\n if (!thing) return null;\n if (isArray(thing)) return thing;\n let i = thing.length;\n if (!isNumber(i)) return null;\n const arr = new Array(i);\n while (i-- > 0) {\n arr[i] = thing[i];\n }\n return arr;\n}\n\n/**\n * Checking if the Uint8Array exists and if it does, it returns a function that checks if the\n * thing passed in is an instance of Uint8Array\n *\n * @param {TypedArray}\n *\n * @returns {Array}\n */\n// eslint-disable-next-line func-names\nconst isTypedArray = (TypedArray => {\n // eslint-disable-next-line func-names\n return thing => {\n return TypedArray && thing instanceof TypedArray;\n };\n})(typeof Uint8Array !== 'undefined' && getPrototypeOf(Uint8Array));\n\n/**\n * For each entry in the object, call the function with the key and value.\n *\n * @param {Object} obj - The object to iterate over.\n * @param {Function} fn - The function to call for each entry.\n *\n * @returns {void}\n */\nconst forEachEntry = (obj, fn) => {\n const generator = obj && obj[Symbol.iterator];\n\n const iterator = generator.call(obj);\n\n let result;\n\n while ((result = iterator.next()) && !result.done) {\n const pair = result.value;\n fn.call(obj, pair[0], pair[1]);\n }\n}\n\n/**\n * It takes a regular expression and a string, and returns an array of all the matches\n *\n * @param {string} regExp - The regular expression to match against.\n * @param {string} str - The string to search.\n *\n * @returns {Array}\n */\nconst matchAll = (regExp, str) => {\n let matches;\n const arr = [];\n\n while ((matches = regExp.exec(str)) !== null) {\n arr.push(matches);\n }\n\n return arr;\n}\n\n/* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */\nconst isHTMLForm = kindOfTest('HTMLFormElement');\n\nconst toCamelCase = str => {\n return str.toLowerCase().replace(/[-_\\s]([a-z\\d])(\\w*)/g,\n function replacer(m, p1, p2) {\n return p1.toUpperCase() + p2;\n }\n );\n};\n\n/* Creating a function that will check if an object has a property. */\nconst hasOwnProperty = (({hasOwnProperty}) => (obj, prop) => hasOwnProperty.call(obj, prop))(Object.prototype);\n\n/**\n * Determine if a value is a RegExp object\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a RegExp object, otherwise false\n */\nconst isRegExp = kindOfTest('RegExp');\n\nconst reduceDescriptors = (obj, reducer) => {\n const descriptors = Object.getOwnPropertyDescriptors(obj);\n const reducedDescriptors = {};\n\n forEach(descriptors, (descriptor, name) => {\n let ret;\n if ((ret = reducer(descriptor, name, obj)) !== false) {\n reducedDescriptors[name] = ret || descriptor;\n }\n });\n\n Object.defineProperties(obj, reducedDescriptors);\n}\n\n/**\n * Makes all methods read-only\n * @param {Object} obj\n */\n\nconst freezeMethods = (obj) => {\n reduceDescriptors(obj, (descriptor, name) => {\n // skip restricted props in strict mode\n if (isFunction(obj) && ['arguments', 'caller', 'callee'].indexOf(name) !== -1) {\n return false;\n }\n\n const value = obj[name];\n\n if (!isFunction(value)) return;\n\n descriptor.enumerable = false;\n\n if ('writable' in descriptor) {\n descriptor.writable = false;\n return;\n }\n\n if (!descriptor.set) {\n descriptor.set = () => {\n throw Error('Can not rewrite read-only method \\'' + name + '\\'');\n };\n }\n });\n}\n\nconst toObjectSet = (arrayOrString, delimiter) => {\n const obj = {};\n\n const define = (arr) => {\n arr.forEach(value => {\n obj[value] = true;\n });\n }\n\n isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter));\n\n return obj;\n}\n\nconst noop = () => {}\n\nconst toFiniteNumber = (value, defaultValue) => {\n return value != null && Number.isFinite(value = +value) ? value : defaultValue;\n}\n\nconst ALPHA = 'abcdefghijklmnopqrstuvwxyz'\n\nconst DIGIT = '0123456789';\n\nconst ALPHABET = {\n DIGIT,\n ALPHA,\n ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT\n}\n\nconst generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT) => {\n let str = '';\n const {length} = alphabet;\n while (size--) {\n str += alphabet[Math.random() * length|0]\n }\n\n return str;\n}\n\n/**\n * If the thing is a FormData object, return true, otherwise return false.\n *\n * @param {unknown} thing - The thing to check.\n *\n * @returns {boolean}\n */\nfunction isSpecCompliantForm(thing) {\n return !!(thing && isFunction(thing.append) && thing[Symbol.toStringTag] === 'FormData' && thing[Symbol.iterator]);\n}\n\nconst toJSONObject = (obj) => {\n const stack = new Array(10);\n\n const visit = (source, i) => {\n\n if (isObject(source)) {\n if (stack.indexOf(source) >= 0) {\n return;\n }\n\n if(!('toJSON' in source)) {\n stack[i] = source;\n const target = isArray(source) ? [] : {};\n\n forEach(source, (value, key) => {\n const reducedValue = visit(value, i + 1);\n !isUndefined(reducedValue) && (target[key] = reducedValue);\n });\n\n stack[i] = undefined;\n\n return target;\n }\n }\n\n return source;\n }\n\n return visit(obj, 0);\n}\n\nconst isAsyncFn = kindOfTest('AsyncFunction');\n\nconst isThenable = (thing) =>\n thing && (isObject(thing) || isFunction(thing)) && isFunction(thing.then) && isFunction(thing.catch);\n\n// original code\n// https://github.com/DigitalBrainJS/AxiosPromise/blob/16deab13710ec09779922131f3fa5954320f83ab/lib/utils.js#L11-L34\n\nconst _setImmediate = ((setImmediateSupported, postMessageSupported) => {\n if (setImmediateSupported) {\n return setImmediate;\n }\n\n return postMessageSupported ? ((token, callbacks) => {\n _global.addEventListener(\"message\", ({source, data}) => {\n if (source === _global && data === token) {\n callbacks.length && callbacks.shift()();\n }\n }, false);\n\n return (cb) => {\n callbacks.push(cb);\n _global.postMessage(token, \"*\");\n }\n })(`axios@${Math.random()}`, []) : (cb) => setTimeout(cb);\n})(\n typeof setImmediate === 'function',\n isFunction(_global.postMessage)\n);\n\nconst asap = typeof queueMicrotask !== 'undefined' ?\n queueMicrotask.bind(_global) : ( typeof process !== 'undefined' && process.nextTick || _setImmediate);\n\n// *********************\n\nexport default {\n isArray,\n isArrayBuffer,\n isBuffer,\n isFormData,\n isArrayBufferView,\n isString,\n isNumber,\n isBoolean,\n isObject,\n isPlainObject,\n isReadableStream,\n isRequest,\n isResponse,\n isHeaders,\n isUndefined,\n isDate,\n isFile,\n isBlob,\n isRegExp,\n isFunction,\n isStream,\n isURLSearchParams,\n isTypedArray,\n isFileList,\n forEach,\n merge,\n extend,\n trim,\n stripBOM,\n inherits,\n toFlatObject,\n kindOf,\n kindOfTest,\n endsWith,\n toArray,\n forEachEntry,\n matchAll,\n isHTMLForm,\n hasOwnProperty,\n hasOwnProp: hasOwnProperty, // an alias to avoid ESLint no-prototype-builtins detection\n reduceDescriptors,\n freezeMethods,\n toObjectSet,\n toCamelCase,\n noop,\n toFiniteNumber,\n findKey,\n global: _global,\n isContextDefined,\n ALPHABET,\n generateString,\n isSpecCompliantForm,\n toJSONObject,\n isAsyncFn,\n isThenable,\n setImmediate: _setImmediate,\n asap\n};\n", "'use strict';\n\nimport utils from '../utils.js';\n\n/**\n * Create an Error with the specified message, config, error code, request and response.\n *\n * @param {string} message The error message.\n * @param {string} [code] The error code (for example, 'ECONNABORTED').\n * @param {Object} [config] The config.\n * @param {Object} [request] The request.\n * @param {Object} [response] The response.\n *\n * @returns {Error} The created error.\n */\nfunction AxiosError(message, code, config, request, response) {\n Error.call(this);\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n } else {\n this.stack = (new Error()).stack;\n }\n\n this.message = message;\n this.name = 'AxiosError';\n code && (this.code = code);\n config && (this.config = config);\n request && (this.request = request);\n if (response) {\n this.response = response;\n this.status = response.status ? response.status : null;\n }\n}\n\nutils.inherits(AxiosError, Error, {\n toJSON: function toJSON() {\n return {\n // Standard\n message: this.message,\n name: this.name,\n // Microsoft\n description: this.description,\n number: this.number,\n // Mozilla\n fileName: this.fileName,\n lineNumber: this.lineNumber,\n columnNumber: this.columnNumber,\n stack: this.stack,\n // Axios\n config: utils.toJSONObject(this.config),\n code: this.code,\n status: this.status\n };\n }\n});\n\nconst prototype = AxiosError.prototype;\nconst descriptors = {};\n\n[\n 'ERR_BAD_OPTION_VALUE',\n 'ERR_BAD_OPTION',\n 'ECONNABORTED',\n 'ETIMEDOUT',\n 'ERR_NETWORK',\n 'ERR_FR_TOO_MANY_REDIRECTS',\n 'ERR_DEPRECATED',\n 'ERR_BAD_RESPONSE',\n 'ERR_BAD_REQUEST',\n 'ERR_CANCELED',\n 'ERR_NOT_SUPPORT',\n 'ERR_INVALID_URL'\n// eslint-disable-next-line func-names\n].forEach(code => {\n descriptors[code] = {value: code};\n});\n\nObject.defineProperties(AxiosError, descriptors);\nObject.defineProperty(prototype, 'isAxiosError', {value: true});\n\n// eslint-disable-next-line func-names\nAxiosError.from = (error, code, config, request, response, customProps) => {\n const axiosError = Object.create(prototype);\n\n utils.toFlatObject(error, axiosError, function filter(obj) {\n return obj !== Error.prototype;\n }, prop => {\n return prop !== 'isAxiosError';\n });\n\n AxiosError.call(axiosError, error.message, code, config, request, response);\n\n axiosError.cause = error;\n\n axiosError.name = error.name;\n\n customProps && Object.assign(axiosError, customProps);\n\n return axiosError;\n};\n\nexport default AxiosError;\n", "// eslint-disable-next-line strict\nexport default null;\n", "'use strict';\n\nimport utils from '../utils.js';\nimport AxiosError from '../core/AxiosError.js';\n// temporary hotfix to avoid circular references until AxiosURLSearchParams is refactored\nimport PlatformFormData from '../platform/node/classes/FormData.js';\n\n/**\n * Determines if the given thing is a array or js object.\n *\n * @param {string} thing - The object or array to be visited.\n *\n * @returns {boolean}\n */\nfunction isVisitable(thing) {\n return utils.isPlainObject(thing) || utils.isArray(thing);\n}\n\n/**\n * It removes the brackets from the end of a string\n *\n * @param {string} key - The key of the parameter.\n *\n * @returns {string} the key without the brackets.\n */\nfunction removeBrackets(key) {\n return utils.endsWith(key, '[]') ? key.slice(0, -2) : key;\n}\n\n/**\n * It takes a path, a key, and a boolean, and returns a string\n *\n * @param {string} path - The path to the current key.\n * @param {string} key - The key of the current object being iterated over.\n * @param {string} dots - If true, the key will be rendered with dots instead of brackets.\n *\n * @returns {string} The path to the current key.\n */\nfunction renderKey(path, key, dots) {\n if (!path) return key;\n return path.concat(key).map(function each(token, i) {\n // eslint-disable-next-line no-param-reassign\n token = removeBrackets(token);\n return !dots && i ? '[' + token + ']' : token;\n }).join(dots ? '.' : '');\n}\n\n/**\n * If the array is an array and none of its elements are visitable, then it's a flat array.\n *\n * @param {Array} arr - The array to check\n *\n * @returns {boolean}\n */\nfunction isFlatArray(arr) {\n return utils.isArray(arr) && !arr.some(isVisitable);\n}\n\nconst predicates = utils.toFlatObject(utils, {}, null, function filter(prop) {\n return /^is[A-Z]/.test(prop);\n});\n\n/**\n * Convert a data object to FormData\n *\n * @param {Object} obj\n * @param {?Object} [formData]\n * @param {?Object} [options]\n * @param {Function} [options.visitor]\n * @param {Boolean} [options.metaTokens = true]\n * @param {Boolean} [options.dots = false]\n * @param {?Boolean} [options.indexes = false]\n *\n * @returns {Object}\n **/\n\n/**\n * It converts an object into a FormData object\n *\n * @param {Object} obj - The object to convert to form data.\n * @param {string} formData - The FormData object to append to.\n * @param {Object} options\n *\n * @returns\n */\nfunction toFormData(obj, formData, options) {\n if (!utils.isObject(obj)) {\n throw new TypeError('target must be an object');\n }\n\n // eslint-disable-next-line no-param-reassign\n formData = formData || new (PlatformFormData || FormData)();\n\n // eslint-disable-next-line no-param-reassign\n options = utils.toFlatObject(options, {\n metaTokens: true,\n dots: false,\n indexes: false\n }, false, function defined(option, source) {\n // eslint-disable-next-line no-eq-null,eqeqeq\n return !utils.isUndefined(source[option]);\n });\n\n const metaTokens = options.metaTokens;\n // eslint-disable-next-line no-use-before-define\n const visitor = options.visitor || defaultVisitor;\n const dots = options.dots;\n const indexes = options.indexes;\n const _Blob = options.Blob || typeof Blob !== 'undefined' && Blob;\n const useBlob = _Blob && utils.isSpecCompliantForm(formData);\n\n if (!utils.isFunction(visitor)) {\n throw new TypeError('visitor must be a function');\n }\n\n function convertValue(value) {\n if (value === null) return '';\n\n if (utils.isDate(value)) {\n return value.toISOString();\n }\n\n if (!useBlob && utils.isBlob(value)) {\n throw new AxiosError('Blob is not supported. Use a Buffer instead.');\n }\n\n if (utils.isArrayBuffer(value) || utils.isTypedArray(value)) {\n return useBlob && typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value);\n }\n\n return value;\n }\n\n /**\n * Default visitor.\n *\n * @param {*} value\n * @param {String|Number} key\n * @param {Array} path\n * @this {FormData}\n *\n * @returns {boolean} return true to visit the each prop of the value recursively\n */\n function defaultVisitor(value, key, path) {\n let arr = value;\n\n if (value && !path && typeof value === 'object') {\n if (utils.endsWith(key, '{}')) {\n // eslint-disable-next-line no-param-reassign\n key = metaTokens ? key : key.slice(0, -2);\n // eslint-disable-next-line no-param-reassign\n value = JSON.stringify(value);\n } else if (\n (utils.isArray(value) && isFlatArray(value)) ||\n ((utils.isFileList(value) || utils.endsWith(key, '[]')) && (arr = utils.toArray(value))\n )) {\n // eslint-disable-next-line no-param-reassign\n key = removeBrackets(key);\n\n arr.forEach(function each(el, index) {\n !(utils.isUndefined(el) || el === null) && formData.append(\n // eslint-disable-next-line no-nested-ternary\n indexes === true ? renderKey([key], index, dots) : (indexes === null ? key : key + '[]'),\n convertValue(el)\n );\n });\n return false;\n }\n }\n\n if (isVisitable(value)) {\n return true;\n }\n\n formData.append(renderKey(path, key, dots), convertValue(value));\n\n return false;\n }\n\n const stack = [];\n\n const exposedHelpers = Object.assign(predicates, {\n defaultVisitor,\n convertValue,\n isVisitable\n });\n\n function build(value, path) {\n if (utils.isUndefined(value)) return;\n\n if (stack.indexOf(value) !== -1) {\n throw Error('Circular reference detected in ' + path.join('.'));\n }\n\n stack.push(value);\n\n utils.forEach(value, function each(el, key) {\n const result = !(utils.isUndefined(el) || el === null) && visitor.call(\n formData, el, utils.isString(key) ? key.trim() : key, path, exposedHelpers\n );\n\n if (result === true) {\n build(el, path ? path.concat(key) : [key]);\n }\n });\n\n stack.pop();\n }\n\n if (!utils.isObject(obj)) {\n throw new TypeError('data must be an object');\n }\n\n build(obj);\n\n return formData;\n}\n\nexport default toFormData;\n", "'use strict';\n\nimport toFormData from './toFormData.js';\n\n/**\n * It encodes a string by replacing all characters that are not in the unreserved set with\n * their percent-encoded equivalents\n *\n * @param {string} str - The string to encode.\n *\n * @returns {string} The encoded string.\n */\nfunction encode(str) {\n const charMap = {\n '!': '%21',\n \"'\": '%27',\n '(': '%28',\n ')': '%29',\n '~': '%7E',\n '%20': '+',\n '%00': '\\x00'\n };\n return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) {\n return charMap[match];\n });\n}\n\n/**\n * It takes a params object and converts it to a FormData object\n *\n * @param {Object} params - The parameters to be converted to a FormData object.\n * @param {Object} options - The options object passed to the Axios constructor.\n *\n * @returns {void}\n */\nfunction AxiosURLSearchParams(params, options) {\n this._pairs = [];\n\n params && toFormData(params, this, options);\n}\n\nconst prototype = AxiosURLSearchParams.prototype;\n\nprototype.append = function append(name, value) {\n this._pairs.push([name, value]);\n};\n\nprototype.toString = function toString(encoder) {\n const _encode = encoder ? function(value) {\n return encoder.call(this, value, encode);\n } : encode;\n\n return this._pairs.map(function each(pair) {\n return _encode(pair[0]) + '=' + _encode(pair[1]);\n }, '').join('&');\n};\n\nexport default AxiosURLSearchParams;\n", "'use strict';\n\nimport utils from '../utils.js';\nimport AxiosURLSearchParams from '../helpers/AxiosURLSearchParams.js';\n\n/**\n * It replaces all instances of the characters `:`, `$`, `,`, `+`, `[`, and `]` with their\n * URI encoded counterparts\n *\n * @param {string} val The value to be encoded.\n *\n * @returns {string} The encoded value.\n */\nfunction encode(val) {\n return encodeURIComponent(val).\n replace(/%3A/gi, ':').\n replace(/%24/g, '$').\n replace(/%2C/gi, ',').\n replace(/%20/g, '+').\n replace(/%5B/gi, '[').\n replace(/%5D/gi, ']');\n}\n\n/**\n * Build a URL by appending params to the end\n *\n * @param {string} url The base of the url (e.g., http://www.google.com)\n * @param {object} [params] The params to be appended\n * @param {?object} options\n *\n * @returns {string} The formatted url\n */\nexport default function buildURL(url, params, options) {\n /*eslint no-param-reassign:0*/\n if (!params) {\n return url;\n }\n \n const _encode = options && options.encode || encode;\n\n const serializeFn = options && options.serialize;\n\n let serializedParams;\n\n if (serializeFn) {\n serializedParams = serializeFn(params, options);\n } else {\n serializedParams = utils.isURLSearchParams(params) ?\n params.toString() :\n new AxiosURLSearchParams(params, options).toString(_encode);\n }\n\n if (serializedParams) {\n const hashmarkIndex = url.indexOf(\"#\");\n\n if (hashmarkIndex !== -1) {\n url = url.slice(0, hashmarkIndex);\n }\n url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;\n }\n\n return url;\n}\n", "'use strict';\n\nimport utils from './../utils.js';\n\nclass InterceptorManager {\n constructor() {\n this.handlers = [];\n }\n\n /**\n * Add a new interceptor to the stack\n *\n * @param {Function} fulfilled The function to handle `then` for a `Promise`\n * @param {Function} rejected The function to handle `reject` for a `Promise`\n *\n * @return {Number} An ID used to remove interceptor later\n */\n use(fulfilled, rejected, options) {\n this.handlers.push({\n fulfilled,\n rejected,\n synchronous: options ? options.synchronous : false,\n runWhen: options ? options.runWhen : null\n });\n return this.handlers.length - 1;\n }\n\n /**\n * Remove an interceptor from the stack\n *\n * @param {Number} id The ID that was returned by `use`\n *\n * @returns {Boolean} `true` if the interceptor was removed, `false` otherwise\n */\n eject(id) {\n if (this.handlers[id]) {\n this.handlers[id] = null;\n }\n }\n\n /**\n * Clear all interceptors from the stack\n *\n * @returns {void}\n */\n clear() {\n if (this.handlers) {\n this.handlers = [];\n }\n }\n\n /**\n * Iterate over all the registered interceptors\n *\n * This method is particularly useful for skipping over any\n * interceptors that may have become `null` calling `eject`.\n *\n * @param {Function} fn The function to call for each interceptor\n *\n * @returns {void}\n */\n forEach(fn) {\n utils.forEach(this.handlers, function forEachHandler(h) {\n if (h !== null) {\n fn(h);\n }\n });\n }\n}\n\nexport default InterceptorManager;\n", "'use strict';\n\nexport default {\n silentJSONParsing: true,\n forcedJSONParsing: true,\n clarifyTimeoutError: false\n};\n", "'use strict';\n\nimport AxiosURLSearchParams from '../../../helpers/AxiosURLSearchParams.js';\nexport default typeof URLSearchParams !== 'undefined' ? URLSearchParams : AxiosURLSearchParams;\n", "'use strict';\n\nexport default typeof FormData !== 'undefined' ? FormData : null;\n", "'use strict'\n\nexport default typeof Blob !== 'undefined' ? Blob : null\n", "import URLSearchParams from './classes/URLSearchParams.js'\nimport FormData from './classes/FormData.js'\nimport Blob from './classes/Blob.js'\n\nexport default {\n isBrowser: true,\n classes: {\n URLSearchParams,\n FormData,\n Blob\n },\n protocols: ['http', 'https', 'file', 'blob', 'url', 'data']\n};\n", "const hasBrowserEnv = typeof window !== 'undefined' && typeof document !== 'undefined';\n\nconst _navigator = typeof navigator === 'object' && navigator || undefined;\n\n/**\n * Determine if we're running in a standard browser environment\n *\n * This allows axios to run in a web worker, and react-native.\n * Both environments support XMLHttpRequest, but not fully standard globals.\n *\n * web workers:\n * typeof window -> undefined\n * typeof document -> undefined\n *\n * react-native:\n * navigator.product -> 'ReactNative'\n * nativescript\n * navigator.product -> 'NativeScript' or 'NS'\n *\n * @returns {boolean}\n */\nconst hasStandardBrowserEnv = hasBrowserEnv &&\n (!_navigator || ['ReactNative', 'NativeScript', 'NS'].indexOf(_navigator.product) < 0);\n\n/**\n * Determine if we're running in a standard browser webWorker environment\n *\n * Although the `isStandardBrowserEnv` method indicates that\n * `allows axios to run in a web worker`, the WebWorker will still be\n * filtered out due to its judgment standard\n * `typeof window !== 'undefined' && typeof document !== 'undefined'`.\n * This leads to a problem when axios post `FormData` in webWorker\n */\nconst hasStandardBrowserWebWorkerEnv = (() => {\n return (\n typeof WorkerGlobalScope !== 'undefined' &&\n // eslint-disable-next-line no-undef\n self instanceof WorkerGlobalScope &&\n typeof self.importScripts === 'function'\n );\n})();\n\nconst origin = hasBrowserEnv && window.location.href || 'http://localhost';\n\nexport {\n hasBrowserEnv,\n hasStandardBrowserWebWorkerEnv,\n hasStandardBrowserEnv,\n _navigator as navigator,\n origin\n}\n", "import platform from './node/index.js';\nimport * as utils from './common/utils.js';\n\nexport default {\n ...utils,\n ...platform\n}\n", "'use strict';\n\nimport utils from '../utils.js';\nimport toFormData from './toFormData.js';\nimport platform from '../platform/index.js';\n\nexport default function toURLEncodedForm(data, options) {\n return toFormData(data, new platform.classes.URLSearchParams(), Object.assign({\n visitor: function(value, key, path, helpers) {\n if (platform.isNode && utils.isBuffer(value)) {\n this.append(key, value.toString('base64'));\n return false;\n }\n\n return helpers.defaultVisitor.apply(this, arguments);\n }\n }, options));\n}\n", "'use strict';\n\nimport utils from '../utils.js';\n\n/**\n * It takes a string like `foo[x][y][z]` and returns an array like `['foo', 'x', 'y', 'z']\n *\n * @param {string} name - The name of the property to get.\n *\n * @returns An array of strings.\n */\nfunction parsePropPath(name) {\n // foo[x][y][z]\n // foo.x.y.z\n // foo-x-y-z\n // foo x y z\n return utils.matchAll(/\\w+|\\[(\\w*)]/g, name).map(match => {\n return match[0] === '[]' ? '' : match[1] || match[0];\n });\n}\n\n/**\n * Convert an array to an object.\n *\n * @param {Array} arr - The array to convert to an object.\n *\n * @returns An object with the same keys and values as the array.\n */\nfunction arrayToObject(arr) {\n const obj = {};\n const keys = Object.keys(arr);\n let i;\n const len = keys.length;\n let key;\n for (i = 0; i < len; i++) {\n key = keys[i];\n obj[key] = arr[key];\n }\n return obj;\n}\n\n/**\n * It takes a FormData object and returns a JavaScript object\n *\n * @param {string} formData The FormData object to convert to JSON.\n *\n * @returns {Object | null} The converted object.\n */\nfunction formDataToJSON(formData) {\n function buildPath(path, value, target, index) {\n let name = path[index++];\n\n if (name === '__proto__') return true;\n\n const isNumericKey = Number.isFinite(+name);\n const isLast = index >= path.length;\n name = !name && utils.isArray(target) ? target.length : name;\n\n if (isLast) {\n if (utils.hasOwnProp(target, name)) {\n target[name] = [target[name], value];\n } else {\n target[name] = value;\n }\n\n return !isNumericKey;\n }\n\n if (!target[name] || !utils.isObject(target[name])) {\n target[name] = [];\n }\n\n const result = buildPath(path, value, target[name], index);\n\n if (result && utils.isArray(target[name])) {\n target[name] = arrayToObject(target[name]);\n }\n\n return !isNumericKey;\n }\n\n if (utils.isFormData(formData) && utils.isFunction(formData.entries)) {\n const obj = {};\n\n utils.forEachEntry(formData, (name, value) => {\n buildPath(parsePropPath(name), value, obj, 0);\n });\n\n return obj;\n }\n\n return null;\n}\n\nexport default formDataToJSON;\n", "'use strict';\n\nimport utils from '../utils.js';\nimport AxiosError from '../core/AxiosError.js';\nimport transitionalDefaults from './transitional.js';\nimport toFormData from '../helpers/toFormData.js';\nimport toURLEncodedForm from '../helpers/toURLEncodedForm.js';\nimport platform from '../platform/index.js';\nimport formDataToJSON from '../helpers/formDataToJSON.js';\n\n/**\n * It takes a string, tries to parse it, and if it fails, it returns the stringified version\n * of the input\n *\n * @param {any} rawValue - The value to be stringified.\n * @param {Function} parser - A function that parses a string into a JavaScript object.\n * @param {Function} encoder - A function that takes a value and returns a string.\n *\n * @returns {string} A stringified version of the rawValue.\n */\nfunction stringifySafely(rawValue, parser, encoder) {\n if (utils.isString(rawValue)) {\n try {\n (parser || JSON.parse)(rawValue);\n return utils.trim(rawValue);\n } catch (e) {\n if (e.name !== 'SyntaxError') {\n throw e;\n }\n }\n }\n\n return (encoder || JSON.stringify)(rawValue);\n}\n\nconst defaults = {\n\n transitional: transitionalDefaults,\n\n adapter: ['xhr', 'http', 'fetch'],\n\n transformRequest: [function transformRequest(data, headers) {\n const contentType = headers.getContentType() || '';\n const hasJSONContentType = contentType.indexOf('application/json') > -1;\n const isObjectPayload = utils.isObject(data);\n\n if (isObjectPayload && utils.isHTMLForm(data)) {\n data = new FormData(data);\n }\n\n const isFormData = utils.isFormData(data);\n\n if (isFormData) {\n return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data;\n }\n\n if (utils.isArrayBuffer(data) ||\n utils.isBuffer(data) ||\n utils.isStream(data) ||\n utils.isFile(data) ||\n utils.isBlob(data) ||\n utils.isReadableStream(data)\n ) {\n return data;\n }\n if (utils.isArrayBufferView(data)) {\n return data.buffer;\n }\n if (utils.isURLSearchParams(data)) {\n headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false);\n return data.toString();\n }\n\n let isFileList;\n\n if (isObjectPayload) {\n if (contentType.indexOf('application/x-www-form-urlencoded') > -1) {\n return toURLEncodedForm(data, this.formSerializer).toString();\n }\n\n if ((isFileList = utils.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) {\n const _FormData = this.env && this.env.FormData;\n\n return toFormData(\n isFileList ? {'files[]': data} : data,\n _FormData && new _FormData(),\n this.formSerializer\n );\n }\n }\n\n if (isObjectPayload || hasJSONContentType ) {\n headers.setContentType('application/json', false);\n return stringifySafely(data);\n }\n\n return data;\n }],\n\n transformResponse: [function transformResponse(data) {\n const transitional = this.transitional || defaults.transitional;\n const forcedJSONParsing = transitional && transitional.forcedJSONParsing;\n const JSONRequested = this.responseType === 'json';\n\n if (utils.isResponse(data) || utils.isReadableStream(data)) {\n return data;\n }\n\n if (data && utils.isString(data) && ((forcedJSONParsing && !this.responseType) || JSONRequested)) {\n const silentJSONParsing = transitional && transitional.silentJSONParsing;\n const strictJSONParsing = !silentJSONParsing && JSONRequested;\n\n try {\n return JSON.parse(data);\n } catch (e) {\n if (strictJSONParsing) {\n if (e.name === 'SyntaxError') {\n throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, this.response);\n }\n throw e;\n }\n }\n }\n\n return data;\n }],\n\n /**\n * A timeout in milliseconds to abort a request. If set to 0 (default) a\n * timeout is not created.\n */\n timeout: 0,\n\n xsrfCookieName: 'XSRF-TOKEN',\n xsrfHeaderName: 'X-XSRF-TOKEN',\n\n maxContentLength: -1,\n maxBodyLength: -1,\n\n env: {\n FormData: platform.classes.FormData,\n Blob: platform.classes.Blob\n },\n\n validateStatus: function validateStatus(status) {\n return status >= 200 && status < 300;\n },\n\n headers: {\n common: {\n 'Accept': 'application/json, text/plain, */*',\n 'Content-Type': undefined\n }\n }\n};\n\nutils.forEach(['delete', 'get', 'head', 'post', 'put', 'patch'], (method) => {\n defaults.headers[method] = {};\n});\n\nexport default defaults;\n", "'use strict';\n\nimport utils from './../utils.js';\n\n// RawAxiosHeaders whose duplicates are ignored by node\n// c.f. https://nodejs.org/api/http.html#http_message_headers\nconst ignoreDuplicateOf = utils.toObjectSet([\n 'age', 'authorization', 'content-length', 'content-type', 'etag',\n 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',\n 'last-modified', 'location', 'max-forwards', 'proxy-authorization',\n 'referer', 'retry-after', 'user-agent'\n]);\n\n/**\n * Parse headers into an object\n *\n * ```\n * Date: Wed, 27 Aug 2014 08:58:49 GMT\n * Content-Type: application/json\n * Connection: keep-alive\n * Transfer-Encoding: chunked\n * ```\n *\n * @param {String} rawHeaders Headers needing to be parsed\n *\n * @returns {Object} Headers parsed into an object\n */\nexport default rawHeaders => {\n const parsed = {};\n let key;\n let val;\n let i;\n\n rawHeaders && rawHeaders.split('\\n').forEach(function parser(line) {\n i = line.indexOf(':');\n key = line.substring(0, i).trim().toLowerCase();\n val = line.substring(i + 1).trim();\n\n if (!key || (parsed[key] && ignoreDuplicateOf[key])) {\n return;\n }\n\n if (key === 'set-cookie') {\n if (parsed[key]) {\n parsed[key].push(val);\n } else {\n parsed[key] = [val];\n }\n } else {\n parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;\n }\n });\n\n return parsed;\n};\n", "'use strict';\n\nimport utils from '../utils.js';\nimport parseHeaders from '../helpers/parseHeaders.js';\n\nconst $internals = Symbol('internals');\n\nfunction normalizeHeader(header) {\n return header && String(header).trim().toLowerCase();\n}\n\nfunction normalizeValue(value) {\n if (value === false || value == null) {\n return value;\n }\n\n return utils.isArray(value) ? value.map(normalizeValue) : String(value);\n}\n\nfunction parseTokens(str) {\n const tokens = Object.create(null);\n const tokensRE = /([^\\s,;=]+)\\s*(?:=\\s*([^,;]+))?/g;\n let match;\n\n while ((match = tokensRE.exec(str))) {\n tokens[match[1]] = match[2];\n }\n\n return tokens;\n}\n\nconst isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim());\n\nfunction matchHeaderValue(context, value, header, filter, isHeaderNameFilter) {\n if (utils.isFunction(filter)) {\n return filter.call(this, value, header);\n }\n\n if (isHeaderNameFilter) {\n value = header;\n }\n\n if (!utils.isString(value)) return;\n\n if (utils.isString(filter)) {\n return value.indexOf(filter) !== -1;\n }\n\n if (utils.isRegExp(filter)) {\n return filter.test(value);\n }\n}\n\nfunction formatHeader(header) {\n return header.trim()\n .toLowerCase().replace(/([a-z\\d])(\\w*)/g, (w, char, str) => {\n return char.toUpperCase() + str;\n });\n}\n\nfunction buildAccessors(obj, header) {\n const accessorName = utils.toCamelCase(' ' + header);\n\n ['get', 'set', 'has'].forEach(methodName => {\n Object.defineProperty(obj, methodName + accessorName, {\n value: function(arg1, arg2, arg3) {\n return this[methodName].call(this, header, arg1, arg2, arg3);\n },\n configurable: true\n });\n });\n}\n\nclass AxiosHeaders {\n constructor(headers) {\n headers && this.set(headers);\n }\n\n set(header, valueOrRewrite, rewrite) {\n const self = this;\n\n function setHeader(_value, _header, _rewrite) {\n const lHeader = normalizeHeader(_header);\n\n if (!lHeader) {\n throw new Error('header name must be a non-empty string');\n }\n\n const key = utils.findKey(self, lHeader);\n\n if(!key || self[key] === undefined || _rewrite === true || (_rewrite === undefined && self[key] !== false)) {\n self[key || _header] = normalizeValue(_value);\n }\n }\n\n const setHeaders = (headers, _rewrite) =>\n utils.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite));\n\n if (utils.isPlainObject(header) || header instanceof this.constructor) {\n setHeaders(header, valueOrRewrite)\n } else if(utils.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {\n setHeaders(parseHeaders(header), valueOrRewrite);\n } else if (utils.isHeaders(header)) {\n for (const [key, value] of header.entries()) {\n setHeader(value, key, rewrite);\n }\n } else {\n header != null && setHeader(valueOrRewrite, header, rewrite);\n }\n\n return this;\n }\n\n get(header, parser) {\n header = normalizeHeader(header);\n\n if (header) {\n const key = utils.findKey(this, header);\n\n if (key) {\n const value = this[key];\n\n if (!parser) {\n return value;\n }\n\n if (parser === true) {\n return parseTokens(value);\n }\n\n if (utils.isFunction(parser)) {\n return parser.call(this, value, key);\n }\n\n if (utils.isRegExp(parser)) {\n return parser.exec(value);\n }\n\n throw new TypeError('parser must be boolean|regexp|function');\n }\n }\n }\n\n has(header, matcher) {\n header = normalizeHeader(header);\n\n if (header) {\n const key = utils.findKey(this, header);\n\n return !!(key && this[key] !== undefined && (!matcher || matchHeaderValue(this, this[key], key, matcher)));\n }\n\n return false;\n }\n\n delete(header, matcher) {\n const self = this;\n let deleted = false;\n\n function deleteHeader(_header) {\n _header = normalizeHeader(_header);\n\n if (_header) {\n const key = utils.findKey(self, _header);\n\n if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) {\n delete self[key];\n\n deleted = true;\n }\n }\n }\n\n if (utils.isArray(header)) {\n header.forEach(deleteHeader);\n } else {\n deleteHeader(header);\n }\n\n return deleted;\n }\n\n clear(matcher) {\n const keys = Object.keys(this);\n let i = keys.length;\n let deleted = false;\n\n while (i--) {\n const key = keys[i];\n if(!matcher || matchHeaderValue(this, this[key], key, matcher, true)) {\n delete this[key];\n deleted = true;\n }\n }\n\n return deleted;\n }\n\n normalize(format) {\n const self = this;\n const headers = {};\n\n utils.forEach(this, (value, header) => {\n const key = utils.findKey(headers, header);\n\n if (key) {\n self[key] = normalizeValue(value);\n delete self[header];\n return;\n }\n\n const normalized = format ? formatHeader(header) : String(header).trim();\n\n if (normalized !== header) {\n delete self[header];\n }\n\n self[normalized] = normalizeValue(value);\n\n headers[normalized] = true;\n });\n\n return this;\n }\n\n concat(...targets) {\n return this.constructor.concat(this, ...targets);\n }\n\n toJSON(asStrings) {\n const obj = Object.create(null);\n\n utils.forEach(this, (value, header) => {\n value != null && value !== false && (obj[header] = asStrings && utils.isArray(value) ? value.join(', ') : value);\n });\n\n return obj;\n }\n\n [Symbol.iterator]() {\n return Object.entries(this.toJSON())[Symbol.iterator]();\n }\n\n toString() {\n return Object.entries(this.toJSON()).map(([header, value]) => header + ': ' + value).join('\\n');\n }\n\n get [Symbol.toStringTag]() {\n return 'AxiosHeaders';\n }\n\n static from(thing) {\n return thing instanceof this ? thing : new this(thing);\n }\n\n static concat(first, ...targets) {\n const computed = new this(first);\n\n targets.forEach((target) => computed.set(target));\n\n return computed;\n }\n\n static accessor(header) {\n const internals = this[$internals] = (this[$internals] = {\n accessors: {}\n });\n\n const accessors = internals.accessors;\n const prototype = this.prototype;\n\n function defineAccessor(_header) {\n const lHeader = normalizeHeader(_header);\n\n if (!accessors[lHeader]) {\n buildAccessors(prototype, _header);\n accessors[lHeader] = true;\n }\n }\n\n utils.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header);\n\n return this;\n }\n}\n\nAxiosHeaders.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent', 'Authorization']);\n\n// reserved names hotfix\nutils.reduceDescriptors(AxiosHeaders.prototype, ({value}, key) => {\n let mapped = key[0].toUpperCase() + key.slice(1); // map `set` => `Set`\n return {\n get: () => value,\n set(headerValue) {\n this[mapped] = headerValue;\n }\n }\n});\n\nutils.freezeMethods(AxiosHeaders);\n\nexport default AxiosHeaders;\n", "'use strict';\n\nimport utils from './../utils.js';\nimport defaults from '../defaults/index.js';\nimport AxiosHeaders from '../core/AxiosHeaders.js';\n\n/**\n * Transform the data for a request or a response\n *\n * @param {Array|Function} fns A single function or Array of functions\n * @param {?Object} response The response object\n *\n * @returns {*} The resulting transformed data\n */\nexport default function transformData(fns, response) {\n const config = this || defaults;\n const context = response || config;\n const headers = AxiosHeaders.from(context.headers);\n let data = context.data;\n\n utils.forEach(fns, function transform(fn) {\n data = fn.call(config, data, headers.normalize(), response ? response.status : undefined);\n });\n\n headers.normalize();\n\n return data;\n}\n", "'use strict';\n\nexport default function isCancel(value) {\n return !!(value && value.__CANCEL__);\n}\n", "'use strict';\n\nimport AxiosError from '../core/AxiosError.js';\nimport utils from '../utils.js';\n\n/**\n * A `CanceledError` is an object that is thrown when an operation is canceled.\n *\n * @param {string=} message The message.\n * @param {Object=} config The config.\n * @param {Object=} request The request.\n *\n * @returns {CanceledError} The created error.\n */\nfunction CanceledError(message, config, request) {\n // eslint-disable-next-line no-eq-null,eqeqeq\n AxiosError.call(this, message == null ? 'canceled' : message, AxiosError.ERR_CANCELED, config, request);\n this.name = 'CanceledError';\n}\n\nutils.inherits(CanceledError, AxiosError, {\n __CANCEL__: true\n});\n\nexport default CanceledError;\n", "'use strict';\n\nimport AxiosError from './AxiosError.js';\n\n/**\n * Resolve or reject a Promise based on response status.\n *\n * @param {Function} resolve A function that resolves the promise.\n * @param {Function} reject A function that rejects the promise.\n * @param {object} response The response.\n *\n * @returns {object} The response.\n */\nexport default function settle(resolve, reject, response) {\n const validateStatus = response.config.validateStatus;\n if (!response.status || !validateStatus || validateStatus(response.status)) {\n resolve(response);\n } else {\n reject(new AxiosError(\n 'Request failed with status code ' + response.status,\n [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4],\n response.config,\n response.request,\n response\n ));\n }\n}\n", "'use strict';\n\nexport default function parseProtocol(url) {\n const match = /^([-+\\w]{1,25})(:?\\/\\/|:)/.exec(url);\n return match && match[1] || '';\n}\n", "'use strict';\n\n/**\n * Calculate data maxRate\n * @param {Number} [samplesCount= 10]\n * @param {Number} [min= 1000]\n * @returns {Function}\n */\nfunction speedometer(samplesCount, min) {\n samplesCount = samplesCount || 10;\n const bytes = new Array(samplesCount);\n const timestamps = new Array(samplesCount);\n let head = 0;\n let tail = 0;\n let firstSampleTS;\n\n min = min !== undefined ? min : 1000;\n\n return function push(chunkLength) {\n const now = Date.now();\n\n const startedAt = timestamps[tail];\n\n if (!firstSampleTS) {\n firstSampleTS = now;\n }\n\n bytes[head] = chunkLength;\n timestamps[head] = now;\n\n let i = tail;\n let bytesCount = 0;\n\n while (i !== head) {\n bytesCount += bytes[i++];\n i = i % samplesCount;\n }\n\n head = (head + 1) % samplesCount;\n\n if (head === tail) {\n tail = (tail + 1) % samplesCount;\n }\n\n if (now - firstSampleTS < min) {\n return;\n }\n\n const passed = startedAt && now - startedAt;\n\n return passed ? Math.round(bytesCount * 1000 / passed) : undefined;\n };\n}\n\nexport default speedometer;\n", "/**\n * Throttle decorator\n * @param {Function} fn\n * @param {Number} freq\n * @return {Function}\n */\nfunction throttle(fn, freq) {\n let timestamp = 0;\n let threshold = 1000 / freq;\n let lastArgs;\n let timer;\n\n const invoke = (args, now = Date.now()) => {\n timestamp = now;\n lastArgs = null;\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n fn.apply(null, args);\n }\n\n const throttled = (...args) => {\n const now = Date.now();\n const passed = now - timestamp;\n if ( passed >= threshold) {\n invoke(args, now);\n } else {\n lastArgs = args;\n if (!timer) {\n timer = setTimeout(() => {\n timer = null;\n invoke(lastArgs)\n }, threshold - passed);\n }\n }\n }\n\n const flush = () => lastArgs && invoke(lastArgs);\n\n return [throttled, flush];\n}\n\nexport default throttle;\n", "import speedometer from \"./speedometer.js\";\nimport throttle from \"./throttle.js\";\nimport utils from \"../utils.js\";\n\nexport const progressEventReducer = (listener, isDownloadStream, freq = 3) => {\n let bytesNotified = 0;\n const _speedometer = speedometer(50, 250);\n\n return throttle(e => {\n const loaded = e.loaded;\n const total = e.lengthComputable ? e.total : undefined;\n const progressBytes = loaded - bytesNotified;\n const rate = _speedometer(progressBytes);\n const inRange = loaded <= total;\n\n bytesNotified = loaded;\n\n const data = {\n loaded,\n total,\n progress: total ? (loaded / total) : undefined,\n bytes: progressBytes,\n rate: rate ? rate : undefined,\n estimated: rate && total && inRange ? (total - loaded) / rate : undefined,\n event: e,\n lengthComputable: total != null,\n [isDownloadStream ? 'download' : 'upload']: true\n };\n\n listener(data);\n }, freq);\n}\n\nexport const progressEventDecorator = (total, throttled) => {\n const lengthComputable = total != null;\n\n return [(loaded) => throttled[0]({\n lengthComputable,\n total,\n loaded\n }), throttled[1]];\n}\n\nexport const asyncDecorator = (fn) => (...args) => utils.asap(() => fn(...args));\n", "'use strict';\n\nimport utils from './../utils.js';\nimport platform from '../platform/index.js';\n\nexport default platform.hasStandardBrowserEnv ?\n\n// Standard browser envs have full support of the APIs needed to test\n// whether the request URL is of the same origin as current location.\n (function standardBrowserEnv() {\n const msie = platform.navigator && /(msie|trident)/i.test(platform.navigator.userAgent);\n const urlParsingNode = document.createElement('a');\n let originURL;\n\n /**\n * Parse a URL to discover its components\n *\n * @param {String} url The URL to be parsed\n * @returns {Object}\n */\n function resolveURL(url) {\n let href = url;\n\n if (msie) {\n // IE needs attribute set twice to normalize properties\n urlParsingNode.setAttribute('href', href);\n href = urlParsingNode.href;\n }\n\n urlParsingNode.setAttribute('href', href);\n\n // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils\n return {\n href: urlParsingNode.href,\n protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',\n host: urlParsingNode.host,\n search: urlParsingNode.search ? urlParsingNode.search.replace(/^\\?/, '') : '',\n hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',\n hostname: urlParsingNode.hostname,\n port: urlParsingNode.port,\n pathname: (urlParsingNode.pathname.charAt(0) === '/') ?\n urlParsingNode.pathname :\n '/' + urlParsingNode.pathname\n };\n }\n\n originURL = resolveURL(window.location.href);\n\n /**\n * Determine if a URL shares the same origin as the current location\n *\n * @param {String} requestURL The URL to test\n * @returns {boolean} True if URL shares the same origin, otherwise false\n */\n return function isURLSameOrigin(requestURL) {\n const parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL;\n return (parsed.protocol === originURL.protocol &&\n parsed.host === originURL.host);\n };\n })() :\n\n // Non standard browser envs (web workers, react-native) lack needed support.\n (function nonStandardBrowserEnv() {\n return function isURLSameOrigin() {\n return true;\n };\n })();\n", "import utils from './../utils.js';\nimport platform from '../platform/index.js';\n\nexport default platform.hasStandardBrowserEnv ?\n\n // Standard browser envs support document.cookie\n {\n write(name, value, expires, path, domain, secure) {\n const cookie = [name + '=' + encodeURIComponent(value)];\n\n utils.isNumber(expires) && cookie.push('expires=' + new Date(expires).toGMTString());\n\n utils.isString(path) && cookie.push('path=' + path);\n\n utils.isString(domain) && cookie.push('domain=' + domain);\n\n secure === true && cookie.push('secure');\n\n document.cookie = cookie.join('; ');\n },\n\n read(name) {\n const match = document.cookie.match(new RegExp('(^|;\\\\s*)(' + name + ')=([^;]*)'));\n return (match ? decodeURIComponent(match[3]) : null);\n },\n\n remove(name) {\n this.write(name, '', Date.now() - 86400000);\n }\n }\n\n :\n\n // Non-standard browser env (web workers, react-native) lack needed support.\n {\n write() {},\n read() {\n return null;\n },\n remove() {}\n };\n\n", "'use strict';\n\n/**\n * Determines whether the specified URL is absolute\n *\n * @param {string} url The URL to test\n *\n * @returns {boolean} True if the specified URL is absolute, otherwise false\n */\nexport default function isAbsoluteURL(url) {\n // A URL is considered absolute if it begins with \"://\" or \"//\" (protocol-relative URL).\n // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed\n // by any combination of letters, digits, plus, period, or hyphen.\n return /^([a-z][a-z\\d+\\-.]*:)?\\/\\//i.test(url);\n}\n", "'use strict';\n\n/**\n * Creates a new URL by combining the specified URLs\n *\n * @param {string} baseURL The base URL\n * @param {string} relativeURL The relative URL\n *\n * @returns {string} The combined URL\n */\nexport default function combineURLs(baseURL, relativeURL) {\n return relativeURL\n ? baseURL.replace(/\\/?\\/$/, '') + '/' + relativeURL.replace(/^\\/+/, '')\n : baseURL;\n}\n", "'use strict';\n\nimport isAbsoluteURL from '../helpers/isAbsoluteURL.js';\nimport combineURLs from '../helpers/combineURLs.js';\n\n/**\n * Creates a new URL by combining the baseURL with the requestedURL,\n * only when the requestedURL is not already an absolute URL.\n * If the requestURL is absolute, this function returns the requestedURL untouched.\n *\n * @param {string} baseURL The base URL\n * @param {string} requestedURL Absolute or relative URL to combine\n *\n * @returns {string} The combined full path\n */\nexport default function buildFullPath(baseURL, requestedURL) {\n if (baseURL && !isAbsoluteURL(requestedURL)) {\n return combineURLs(baseURL, requestedURL);\n }\n return requestedURL;\n}\n", "'use strict';\n\nimport utils from '../utils.js';\nimport AxiosHeaders from \"./AxiosHeaders.js\";\n\nconst headersToObject = (thing) => thing instanceof AxiosHeaders ? { ...thing } : thing;\n\n/**\n * Config-specific merge-function which creates a new config-object\n * by merging two configuration objects together.\n *\n * @param {Object} config1\n * @param {Object} config2\n *\n * @returns {Object} New object resulting from merging config2 to config1\n */\nexport default function mergeConfig(config1, config2) {\n // eslint-disable-next-line no-param-reassign\n config2 = config2 || {};\n const config = {};\n\n function getMergedValue(target, source, caseless) {\n if (utils.isPlainObject(target) && utils.isPlainObject(source)) {\n return utils.merge.call({caseless}, target, source);\n } else if (utils.isPlainObject(source)) {\n return utils.merge({}, source);\n } else if (utils.isArray(source)) {\n return source.slice();\n }\n return source;\n }\n\n // eslint-disable-next-line consistent-return\n function mergeDeepProperties(a, b, caseless) {\n if (!utils.isUndefined(b)) {\n return getMergedValue(a, b, caseless);\n } else if (!utils.isUndefined(a)) {\n return getMergedValue(undefined, a, caseless);\n }\n }\n\n // eslint-disable-next-line consistent-return\n function valueFromConfig2(a, b) {\n if (!utils.isUndefined(b)) {\n return getMergedValue(undefined, b);\n }\n }\n\n // eslint-disable-next-line consistent-return\n function defaultToConfig2(a, b) {\n if (!utils.isUndefined(b)) {\n return getMergedValue(undefined, b);\n } else if (!utils.isUndefined(a)) {\n return getMergedValue(undefined, a);\n }\n }\n\n // eslint-disable-next-line consistent-return\n function mergeDirectKeys(a, b, prop) {\n if (prop in config2) {\n return getMergedValue(a, b);\n } else if (prop in config1) {\n return getMergedValue(undefined, a);\n }\n }\n\n const mergeMap = {\n url: valueFromConfig2,\n method: valueFromConfig2,\n data: valueFromConfig2,\n baseURL: defaultToConfig2,\n transformRequest: defaultToConfig2,\n transformResponse: defaultToConfig2,\n paramsSerializer: defaultToConfig2,\n timeout: defaultToConfig2,\n timeoutMessage: defaultToConfig2,\n withCredentials: defaultToConfig2,\n withXSRFToken: defaultToConfig2,\n adapter: defaultToConfig2,\n responseType: defaultToConfig2,\n xsrfCookieName: defaultToConfig2,\n xsrfHeaderName: defaultToConfig2,\n onUploadProgress: defaultToConfig2,\n onDownloadProgress: defaultToConfig2,\n decompress: defaultToConfig2,\n maxContentLength: defaultToConfig2,\n maxBodyLength: defaultToConfig2,\n beforeRedirect: defaultToConfig2,\n transport: defaultToConfig2,\n httpAgent: defaultToConfig2,\n httpsAgent: defaultToConfig2,\n cancelToken: defaultToConfig2,\n socketPath: defaultToConfig2,\n responseEncoding: defaultToConfig2,\n validateStatus: mergeDirectKeys,\n headers: (a, b) => mergeDeepProperties(headersToObject(a), headersToObject(b), true)\n };\n\n utils.forEach(Object.keys(Object.assign({}, config1, config2)), function computeConfigValue(prop) {\n const merge = mergeMap[prop] || mergeDeepProperties;\n const configValue = merge(config1[prop], config2[prop], prop);\n (utils.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);\n });\n\n return config;\n}\n", "import platform from \"../platform/index.js\";\nimport utils from \"../utils.js\";\nimport isURLSameOrigin from \"./isURLSameOrigin.js\";\nimport cookies from \"./cookies.js\";\nimport buildFullPath from \"../core/buildFullPath.js\";\nimport mergeConfig from \"../core/mergeConfig.js\";\nimport AxiosHeaders from \"../core/AxiosHeaders.js\";\nimport buildURL from \"./buildURL.js\";\n\nexport default (config) => {\n const newConfig = mergeConfig({}, config);\n\n let {data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth} = newConfig;\n\n newConfig.headers = headers = AxiosHeaders.from(headers);\n\n newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url), config.params, config.paramsSerializer);\n\n // HTTP basic authentication\n if (auth) {\n headers.set('Authorization', 'Basic ' +\n btoa((auth.username || '') + ':' + (auth.password ? unescape(encodeURIComponent(auth.password)) : ''))\n );\n }\n\n let contentType;\n\n if (utils.isFormData(data)) {\n if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) {\n headers.setContentType(undefined); // Let the browser set it\n } else if ((contentType = headers.getContentType()) !== false) {\n // fix semicolon duplication issue for ReactNative FormData implementation\n const [type, ...tokens] = contentType ? contentType.split(';').map(token => token.trim()).filter(Boolean) : [];\n headers.setContentType([type || 'multipart/form-data', ...tokens].join('; '));\n }\n }\n\n // Add xsrf header\n // This is only done if running in a standard browser environment.\n // Specifically not if we're in a web worker, or react-native.\n\n if (platform.hasStandardBrowserEnv) {\n withXSRFToken && utils.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(newConfig));\n\n if (withXSRFToken || (withXSRFToken !== false && isURLSameOrigin(newConfig.url))) {\n // Add xsrf header\n const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName);\n\n if (xsrfValue) {\n headers.set(xsrfHeaderName, xsrfValue);\n }\n }\n }\n\n return newConfig;\n}\n\n", "import utils from './../utils.js';\nimport settle from './../core/settle.js';\nimport transitionalDefaults from '../defaults/transitional.js';\nimport AxiosError from '../core/AxiosError.js';\nimport CanceledError from '../cancel/CanceledError.js';\nimport parseProtocol from '../helpers/parseProtocol.js';\nimport platform from '../platform/index.js';\nimport AxiosHeaders from '../core/AxiosHeaders.js';\nimport {progressEventReducer} from '../helpers/progressEventReducer.js';\nimport resolveConfig from \"../helpers/resolveConfig.js\";\n\nconst isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined';\n\nexport default isXHRAdapterSupported && function (config) {\n return new Promise(function dispatchXhrRequest(resolve, reject) {\n const _config = resolveConfig(config);\n let requestData = _config.data;\n const requestHeaders = AxiosHeaders.from(_config.headers).normalize();\n let {responseType, onUploadProgress, onDownloadProgress} = _config;\n let onCanceled;\n let uploadThrottled, downloadThrottled;\n let flushUpload, flushDownload;\n\n function done() {\n flushUpload && flushUpload(); // flush events\n flushDownload && flushDownload(); // flush events\n\n _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled);\n\n _config.signal && _config.signal.removeEventListener('abort', onCanceled);\n }\n\n let request = new XMLHttpRequest();\n\n request.open(_config.method.toUpperCase(), _config.url, true);\n\n // Set the request timeout in MS\n request.timeout = _config.timeout;\n\n function onloadend() {\n if (!request) {\n return;\n }\n // Prepare the response\n const responseHeaders = AxiosHeaders.from(\n 'getAllResponseHeaders' in request && request.getAllResponseHeaders()\n );\n const responseData = !responseType || responseType === 'text' || responseType === 'json' ?\n request.responseText : request.response;\n const response = {\n data: responseData,\n status: request.status,\n statusText: request.statusText,\n headers: responseHeaders,\n config,\n request\n };\n\n settle(function _resolve(value) {\n resolve(value);\n done();\n }, function _reject(err) {\n reject(err);\n done();\n }, response);\n\n // Clean up request\n request = null;\n }\n\n if ('onloadend' in request) {\n // Use onloadend if available\n request.onloadend = onloadend;\n } else {\n // Listen for ready state to emulate onloadend\n request.onreadystatechange = function handleLoad() {\n if (!request || request.readyState !== 4) {\n return;\n }\n\n // The request errored out and we didn't get a response, this will be\n // handled by onerror instead\n // With one exception: request that using file: protocol, most browsers\n // will return status as 0 even though it's a successful request\n if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {\n return;\n }\n // readystate handler is calling before onerror or ontimeout handlers,\n // so we should call onloadend on the next 'tick'\n setTimeout(onloadend);\n };\n }\n\n // Handle browser request cancellation (as opposed to a manual cancellation)\n request.onabort = function handleAbort() {\n if (!request) {\n return;\n }\n\n reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request));\n\n // Clean up request\n request = null;\n };\n\n // Handle low level network errors\n request.onerror = function handleError() {\n // Real errors are hidden from us by the browser\n // onerror should only fire if it's a network error\n reject(new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request));\n\n // Clean up request\n request = null;\n };\n\n // Handle timeout\n request.ontimeout = function handleTimeout() {\n let timeoutErrorMessage = _config.timeout ? 'timeout of ' + _config.timeout + 'ms exceeded' : 'timeout exceeded';\n const transitional = _config.transitional || transitionalDefaults;\n if (_config.timeoutErrorMessage) {\n timeoutErrorMessage = _config.timeoutErrorMessage;\n }\n reject(new AxiosError(\n timeoutErrorMessage,\n transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED,\n config,\n request));\n\n // Clean up request\n request = null;\n };\n\n // Remove Content-Type if data is undefined\n requestData === undefined && requestHeaders.setContentType(null);\n\n // Add headers to the request\n if ('setRequestHeader' in request) {\n utils.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) {\n request.setRequestHeader(key, val);\n });\n }\n\n // Add withCredentials to request if needed\n if (!utils.isUndefined(_config.withCredentials)) {\n request.withCredentials = !!_config.withCredentials;\n }\n\n // Add responseType to request if needed\n if (responseType && responseType !== 'json') {\n request.responseType = _config.responseType;\n }\n\n // Handle progress if needed\n if (onDownloadProgress) {\n ([downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true));\n request.addEventListener('progress', downloadThrottled);\n }\n\n // Not all browsers support upload events\n if (onUploadProgress && request.upload) {\n ([uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress));\n\n request.upload.addEventListener('progress', uploadThrottled);\n\n request.upload.addEventListener('loadend', flushUpload);\n }\n\n if (_config.cancelToken || _config.signal) {\n // Handle cancellation\n // eslint-disable-next-line func-names\n onCanceled = cancel => {\n if (!request) {\n return;\n }\n reject(!cancel || cancel.type ? new CanceledError(null, config, request) : cancel);\n request.abort();\n request = null;\n };\n\n _config.cancelToken && _config.cancelToken.subscribe(onCanceled);\n if (_config.signal) {\n _config.signal.aborted ? onCanceled() : _config.signal.addEventListener('abort', onCanceled);\n }\n }\n\n const protocol = parseProtocol(_config.url);\n\n if (protocol && platform.protocols.indexOf(protocol) === -1) {\n reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config));\n return;\n }\n\n\n // Send the request\n request.send(requestData || null);\n });\n}\n", "import CanceledError from \"../cancel/CanceledError.js\";\nimport AxiosError from \"../core/AxiosError.js\";\nimport utils from '../utils.js';\n\nconst composeSignals = (signals, timeout) => {\n const {length} = (signals = signals ? signals.filter(Boolean) : []);\n\n if (timeout || length) {\n let controller = new AbortController();\n\n let aborted;\n\n const onabort = function (reason) {\n if (!aborted) {\n aborted = true;\n unsubscribe();\n const err = reason instanceof Error ? reason : this.reason;\n controller.abort(err instanceof AxiosError ? err : new CanceledError(err instanceof Error ? err.message : err));\n }\n }\n\n let timer = timeout && setTimeout(() => {\n timer = null;\n onabort(new AxiosError(`timeout ${timeout} of ms exceeded`, AxiosError.ETIMEDOUT))\n }, timeout)\n\n const unsubscribe = () => {\n if (signals) {\n timer && clearTimeout(timer);\n timer = null;\n signals.forEach(signal => {\n signal.unsubscribe ? signal.unsubscribe(onabort) : signal.removeEventListener('abort', onabort);\n });\n signals = null;\n }\n }\n\n signals.forEach((signal) => signal.addEventListener('abort', onabort));\n\n const {signal} = controller;\n\n signal.unsubscribe = () => utils.asap(unsubscribe);\n\n return signal;\n }\n}\n\nexport default composeSignals;\n", "\nexport const streamChunk = function* (chunk, chunkSize) {\n let len = chunk.byteLength;\n\n if (!chunkSize || len < chunkSize) {\n yield chunk;\n return;\n }\n\n let pos = 0;\n let end;\n\n while (pos < len) {\n end = pos + chunkSize;\n yield chunk.slice(pos, end);\n pos = end;\n }\n}\n\nexport const readBytes = async function* (iterable, chunkSize) {\n for await (const chunk of readStream(iterable)) {\n yield* streamChunk(chunk, chunkSize);\n }\n}\n\nconst readStream = async function* (stream) {\n if (stream[Symbol.asyncIterator]) {\n yield* stream;\n return;\n }\n\n const reader = stream.getReader();\n try {\n for (;;) {\n const {done, value} = await reader.read();\n if (done) {\n break;\n }\n yield value;\n }\n } finally {\n await reader.cancel();\n }\n}\n\nexport const trackStream = (stream, chunkSize, onProgress, onFinish) => {\n const iterator = readBytes(stream, chunkSize);\n\n let bytes = 0;\n let done;\n let _onFinish = (e) => {\n if (!done) {\n done = true;\n onFinish && onFinish(e);\n }\n }\n\n return new ReadableStream({\n async pull(controller) {\n try {\n const {done, value} = await iterator.next();\n\n if (done) {\n _onFinish();\n controller.close();\n return;\n }\n\n let len = value.byteLength;\n if (onProgress) {\n let loadedBytes = bytes += len;\n onProgress(loadedBytes);\n }\n controller.enqueue(new Uint8Array(value));\n } catch (err) {\n _onFinish(err);\n throw err;\n }\n },\n cancel(reason) {\n _onFinish(reason);\n return iterator.return();\n }\n }, {\n highWaterMark: 2\n })\n}\n", "import platform from \"../platform/index.js\";\nimport utils from \"../utils.js\";\nimport AxiosError from \"../core/AxiosError.js\";\nimport composeSignals from \"../helpers/composeSignals.js\";\nimport {trackStream} from \"../helpers/trackStream.js\";\nimport AxiosHeaders from \"../core/AxiosHeaders.js\";\nimport {progressEventReducer, progressEventDecorator, asyncDecorator} from \"../helpers/progressEventReducer.js\";\nimport resolveConfig from \"../helpers/resolveConfig.js\";\nimport settle from \"../core/settle.js\";\n\nconst isFetchSupported = typeof fetch === 'function' && typeof Request === 'function' && typeof Response === 'function';\nconst isReadableStreamSupported = isFetchSupported && typeof ReadableStream === 'function';\n\n// used only inside the fetch adapter\nconst encodeText = isFetchSupported && (typeof TextEncoder === 'function' ?\n ((encoder) => (str) => encoder.encode(str))(new TextEncoder()) :\n async (str) => new Uint8Array(await new Response(str).arrayBuffer())\n);\n\nconst test = (fn, ...args) => {\n try {\n return !!fn(...args);\n } catch (e) {\n return false\n }\n}\n\nconst supportsRequestStream = isReadableStreamSupported && test(() => {\n let duplexAccessed = false;\n\n const hasContentType = new Request(platform.origin, {\n body: new ReadableStream(),\n method: 'POST',\n get duplex() {\n duplexAccessed = true;\n return 'half';\n },\n }).headers.has('Content-Type');\n\n return duplexAccessed && !hasContentType;\n});\n\nconst DEFAULT_CHUNK_SIZE = 64 * 1024;\n\nconst supportsResponseStream = isReadableStreamSupported &&\n test(() => utils.isReadableStream(new Response('').body));\n\n\nconst resolvers = {\n stream: supportsResponseStream && ((res) => res.body)\n};\n\nisFetchSupported && (((res) => {\n ['text', 'arrayBuffer', 'blob', 'formData', 'stream'].forEach(type => {\n !resolvers[type] && (resolvers[type] = utils.isFunction(res[type]) ? (res) => res[type]() :\n (_, config) => {\n throw new AxiosError(`Response type '${type}' is not supported`, AxiosError.ERR_NOT_SUPPORT, config);\n })\n });\n})(new Response));\n\nconst getBodyLength = async (body) => {\n if (body == null) {\n return 0;\n }\n\n if(utils.isBlob(body)) {\n return body.size;\n }\n\n if(utils.isSpecCompliantForm(body)) {\n const _request = new Request(platform.origin, {\n method: 'POST',\n body,\n });\n return (await _request.arrayBuffer()).byteLength;\n }\n\n if(utils.isArrayBufferView(body) || utils.isArrayBuffer(body)) {\n return body.byteLength;\n }\n\n if(utils.isURLSearchParams(body)) {\n body = body + '';\n }\n\n if(utils.isString(body)) {\n return (await encodeText(body)).byteLength;\n }\n}\n\nconst resolveBodyLength = async (headers, body) => {\n const length = utils.toFiniteNumber(headers.getContentLength());\n\n return length == null ? getBodyLength(body) : length;\n}\n\nexport default isFetchSupported && (async (config) => {\n let {\n url,\n method,\n data,\n signal,\n cancelToken,\n timeout,\n onDownloadProgress,\n onUploadProgress,\n responseType,\n headers,\n withCredentials = 'same-origin',\n fetchOptions\n } = resolveConfig(config);\n\n responseType = responseType ? (responseType + '').toLowerCase() : 'text';\n\n let composedSignal = composeSignals([signal, cancelToken && cancelToken.toAbortSignal()], timeout);\n\n let request;\n\n const unsubscribe = composedSignal && composedSignal.unsubscribe && (() => {\n composedSignal.unsubscribe();\n });\n\n let requestContentLength;\n\n try {\n if (\n onUploadProgress && supportsRequestStream && method !== 'get' && method !== 'head' &&\n (requestContentLength = await resolveBodyLength(headers, data)) !== 0\n ) {\n let _request = new Request(url, {\n method: 'POST',\n body: data,\n duplex: \"half\"\n });\n\n let contentTypeHeader;\n\n if (utils.isFormData(data) && (contentTypeHeader = _request.headers.get('content-type'))) {\n headers.setContentType(contentTypeHeader)\n }\n\n if (_request.body) {\n const [onProgress, flush] = progressEventDecorator(\n requestContentLength,\n progressEventReducer(asyncDecorator(onUploadProgress))\n );\n\n data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, onProgress, flush);\n }\n }\n\n if (!utils.isString(withCredentials)) {\n withCredentials = withCredentials ? 'include' : 'omit';\n }\n\n // Cloudflare Workers throws when credentials are defined\n // see https://github.com/cloudflare/workerd/issues/902\n const isCredentialsSupported = \"credentials\" in Request.prototype;\n request = new Request(url, {\n ...fetchOptions,\n signal: composedSignal,\n method: method.toUpperCase(),\n headers: headers.normalize().toJSON(),\n body: data,\n duplex: \"half\",\n credentials: isCredentialsSupported ? withCredentials : undefined\n });\n\n let response = await fetch(request);\n\n const isStreamResponse = supportsResponseStream && (responseType === 'stream' || responseType === 'response');\n\n if (supportsResponseStream && (onDownloadProgress || (isStreamResponse && unsubscribe))) {\n const options = {};\n\n ['status', 'statusText', 'headers'].forEach(prop => {\n options[prop] = response[prop];\n });\n\n const responseContentLength = utils.toFiniteNumber(response.headers.get('content-length'));\n\n const [onProgress, flush] = onDownloadProgress && progressEventDecorator(\n responseContentLength,\n progressEventReducer(asyncDecorator(onDownloadProgress), true)\n ) || [];\n\n response = new Response(\n trackStream(response.body, DEFAULT_CHUNK_SIZE, onProgress, () => {\n flush && flush();\n unsubscribe && unsubscribe();\n }),\n options\n );\n }\n\n responseType = responseType || 'text';\n\n let responseData = await resolvers[utils.findKey(resolvers, responseType) || 'text'](response, config);\n\n !isStreamResponse && unsubscribe && unsubscribe();\n\n return await new Promise((resolve, reject) => {\n settle(resolve, reject, {\n data: responseData,\n headers: AxiosHeaders.from(response.headers),\n status: response.status,\n statusText: response.statusText,\n config,\n request\n })\n })\n } catch (err) {\n unsubscribe && unsubscribe();\n\n if (err && err.name === 'TypeError' && /fetch/i.test(err.message)) {\n throw Object.assign(\n new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request),\n {\n cause: err.cause || err\n }\n )\n }\n\n throw AxiosError.from(err, err && err.code, config, request);\n }\n});\n\n\n", "import utils from '../utils.js';\nimport httpAdapter from './http.js';\nimport xhrAdapter from './xhr.js';\nimport fetchAdapter from './fetch.js';\nimport AxiosError from \"../core/AxiosError.js\";\n\nconst knownAdapters = {\n http: httpAdapter,\n xhr: xhrAdapter,\n fetch: fetchAdapter\n}\n\nutils.forEach(knownAdapters, (fn, value) => {\n if (fn) {\n try {\n Object.defineProperty(fn, 'name', {value});\n } catch (e) {\n // eslint-disable-next-line no-empty\n }\n Object.defineProperty(fn, 'adapterName', {value});\n }\n});\n\nconst renderReason = (reason) => `- ${reason}`;\n\nconst isResolvedHandle = (adapter) => utils.isFunction(adapter) || adapter === null || adapter === false;\n\nexport default {\n getAdapter: (adapters) => {\n adapters = utils.isArray(adapters) ? adapters : [adapters];\n\n const {length} = adapters;\n let nameOrAdapter;\n let adapter;\n\n const rejectedReasons = {};\n\n for (let i = 0; i < length; i++) {\n nameOrAdapter = adapters[i];\n let id;\n\n adapter = nameOrAdapter;\n\n if (!isResolvedHandle(nameOrAdapter)) {\n adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()];\n\n if (adapter === undefined) {\n throw new AxiosError(`Unknown adapter '${id}'`);\n }\n }\n\n if (adapter) {\n break;\n }\n\n rejectedReasons[id || '#' + i] = adapter;\n }\n\n if (!adapter) {\n\n const reasons = Object.entries(rejectedReasons)\n .map(([id, state]) => `adapter ${id} ` +\n (state === false ? 'is not supported by the environment' : 'is not available in the build')\n );\n\n let s = length ?\n (reasons.length > 1 ? 'since :\\n' + reasons.map(renderReason).join('\\n') : ' ' + renderReason(reasons[0])) :\n 'as no adapter specified';\n\n throw new AxiosError(\n `There is no suitable adapter to dispatch the request ` + s,\n 'ERR_NOT_SUPPORT'\n );\n }\n\n return adapter;\n },\n adapters: knownAdapters\n}\n", "'use strict';\n\nimport transformData from './transformData.js';\nimport isCancel from '../cancel/isCancel.js';\nimport defaults from '../defaults/index.js';\nimport CanceledError from '../cancel/CanceledError.js';\nimport AxiosHeaders from '../core/AxiosHeaders.js';\nimport adapters from \"../adapters/adapters.js\";\n\n/**\n * Throws a `CanceledError` if cancellation has been requested.\n *\n * @param {Object} config The config that is to be used for the request\n *\n * @returns {void}\n */\nfunction throwIfCancellationRequested(config) {\n if (config.cancelToken) {\n config.cancelToken.throwIfRequested();\n }\n\n if (config.signal && config.signal.aborted) {\n throw new CanceledError(null, config);\n }\n}\n\n/**\n * Dispatch a request to the server using the configured adapter.\n *\n * @param {object} config The config that is to be used for the request\n *\n * @returns {Promise} The Promise to be fulfilled\n */\nexport default function dispatchRequest(config) {\n throwIfCancellationRequested(config);\n\n config.headers = AxiosHeaders.from(config.headers);\n\n // Transform request data\n config.data = transformData.call(\n config,\n config.transformRequest\n );\n\n if (['post', 'put', 'patch'].indexOf(config.method) !== -1) {\n config.headers.setContentType('application/x-www-form-urlencoded', false);\n }\n\n const adapter = adapters.getAdapter(config.adapter || defaults.adapter);\n\n return adapter(config).then(function onAdapterResolution(response) {\n throwIfCancellationRequested(config);\n\n // Transform response data\n response.data = transformData.call(\n config,\n config.transformResponse,\n response\n );\n\n response.headers = AxiosHeaders.from(response.headers);\n\n return response;\n }, function onAdapterRejection(reason) {\n if (!isCancel(reason)) {\n throwIfCancellationRequested(config);\n\n // Transform response data\n if (reason && reason.response) {\n reason.response.data = transformData.call(\n config,\n config.transformResponse,\n reason.response\n );\n reason.response.headers = AxiosHeaders.from(reason.response.headers);\n }\n }\n\n return Promise.reject(reason);\n });\n}\n", "export const VERSION = \"1.7.7\";", "'use strict';\n\nimport {VERSION} from '../env/data.js';\nimport AxiosError from '../core/AxiosError.js';\n\nconst validators = {};\n\n// eslint-disable-next-line func-names\n['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach((type, i) => {\n validators[type] = function validator(thing) {\n return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type;\n };\n});\n\nconst deprecatedWarnings = {};\n\n/**\n * Transitional option validator\n *\n * @param {function|boolean?} validator - set to false if the transitional option has been removed\n * @param {string?} version - deprecated version / removed since version\n * @param {string?} message - some message with additional info\n *\n * @returns {function}\n */\nvalidators.transitional = function transitional(validator, version, message) {\n function formatMessage(opt, desc) {\n return '[Axios v' + VERSION + '] Transitional option \\'' + opt + '\\'' + desc + (message ? '. ' + message : '');\n }\n\n // eslint-disable-next-line func-names\n return (value, opt, opts) => {\n if (validator === false) {\n throw new AxiosError(\n formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')),\n AxiosError.ERR_DEPRECATED\n );\n }\n\n if (version && !deprecatedWarnings[opt]) {\n deprecatedWarnings[opt] = true;\n // eslint-disable-next-line no-console\n console.warn(\n formatMessage(\n opt,\n ' has been deprecated since v' + version + ' and will be removed in the near future'\n )\n );\n }\n\n return validator ? validator(value, opt, opts) : true;\n };\n};\n\n/**\n * Assert object's properties type\n *\n * @param {object} options\n * @param {object} schema\n * @param {boolean?} allowUnknown\n *\n * @returns {object}\n */\n\nfunction assertOptions(options, schema, allowUnknown) {\n if (typeof options !== 'object') {\n throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE);\n }\n const keys = Object.keys(options);\n let i = keys.length;\n while (i-- > 0) {\n const opt = keys[i];\n const validator = schema[opt];\n if (validator) {\n const value = options[opt];\n const result = value === undefined || validator(value, opt, options);\n if (result !== true) {\n throw new AxiosError('option ' + opt + ' must be ' + result, AxiosError.ERR_BAD_OPTION_VALUE);\n }\n continue;\n }\n if (allowUnknown !== true) {\n throw new AxiosError('Unknown option ' + opt, AxiosError.ERR_BAD_OPTION);\n }\n }\n}\n\nexport default {\n assertOptions,\n validators\n};\n", "'use strict';\n\nimport utils from './../utils.js';\nimport buildURL from '../helpers/buildURL.js';\nimport InterceptorManager from './InterceptorManager.js';\nimport dispatchRequest from './dispatchRequest.js';\nimport mergeConfig from './mergeConfig.js';\nimport buildFullPath from './buildFullPath.js';\nimport validator from '../helpers/validator.js';\nimport AxiosHeaders from './AxiosHeaders.js';\n\nconst validators = validator.validators;\n\n/**\n * Create a new instance of Axios\n *\n * @param {Object} instanceConfig The default config for the instance\n *\n * @return {Axios} A new instance of Axios\n */\nclass Axios {\n constructor(instanceConfig) {\n this.defaults = instanceConfig;\n this.interceptors = {\n request: new InterceptorManager(),\n response: new InterceptorManager()\n };\n }\n\n /**\n * Dispatch a request\n *\n * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults)\n * @param {?Object} config\n *\n * @returns {Promise} The Promise to be fulfilled\n */\n async request(configOrUrl, config) {\n try {\n return await this._request(configOrUrl, config);\n } catch (err) {\n if (err instanceof Error) {\n let dummy;\n\n Error.captureStackTrace ? Error.captureStackTrace(dummy = {}) : (dummy = new Error());\n\n // slice off the Error: ... line\n const stack = dummy.stack ? dummy.stack.replace(/^.+\\n/, '') : '';\n try {\n if (!err.stack) {\n err.stack = stack;\n // match without the 2 top stack lines\n } else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\\n.+\\n/, ''))) {\n err.stack += '\\n' + stack\n }\n } catch (e) {\n // ignore the case where \"stack\" is an un-writable property\n }\n }\n\n throw err;\n }\n }\n\n _request(configOrUrl, config) {\n /*eslint no-param-reassign:0*/\n // Allow for axios('example/url'[, config]) a la fetch API\n if (typeof configOrUrl === 'string') {\n config = config || {};\n config.url = configOrUrl;\n } else {\n config = configOrUrl || {};\n }\n\n config = mergeConfig(this.defaults, config);\n\n const {transitional, paramsSerializer, headers} = config;\n\n if (transitional !== undefined) {\n validator.assertOptions(transitional, {\n silentJSONParsing: validators.transitional(validators.boolean),\n forcedJSONParsing: validators.transitional(validators.boolean),\n clarifyTimeoutError: validators.transitional(validators.boolean)\n }, false);\n }\n\n if (paramsSerializer != null) {\n if (utils.isFunction(paramsSerializer)) {\n config.paramsSerializer = {\n serialize: paramsSerializer\n }\n } else {\n validator.assertOptions(paramsSerializer, {\n encode: validators.function,\n serialize: validators.function\n }, true);\n }\n }\n\n // Set config.method\n config.method = (config.method || this.defaults.method || 'get').toLowerCase();\n\n // Flatten headers\n let contextHeaders = headers && utils.merge(\n headers.common,\n headers[config.method]\n );\n\n headers && utils.forEach(\n ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],\n (method) => {\n delete headers[method];\n }\n );\n\n config.headers = AxiosHeaders.concat(contextHeaders, headers);\n\n // filter out skipped interceptors\n const requestInterceptorChain = [];\n let synchronousRequestInterceptors = true;\n this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {\n if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {\n return;\n }\n\n synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;\n\n requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);\n });\n\n const responseInterceptorChain = [];\n this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {\n responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);\n });\n\n let promise;\n let i = 0;\n let len;\n\n if (!synchronousRequestInterceptors) {\n const chain = [dispatchRequest.bind(this), undefined];\n chain.unshift.apply(chain, requestInterceptorChain);\n chain.push.apply(chain, responseInterceptorChain);\n len = chain.length;\n\n promise = Promise.resolve(config);\n\n while (i < len) {\n promise = promise.then(chain[i++], chain[i++]);\n }\n\n return promise;\n }\n\n len = requestInterceptorChain.length;\n\n let newConfig = config;\n\n i = 0;\n\n while (i < len) {\n const onFulfilled = requestInterceptorChain[i++];\n const onRejected = requestInterceptorChain[i++];\n try {\n newConfig = onFulfilled(newConfig);\n } catch (error) {\n onRejected.call(this, error);\n break;\n }\n }\n\n try {\n promise = dispatchRequest.call(this, newConfig);\n } catch (error) {\n return Promise.reject(error);\n }\n\n i = 0;\n len = responseInterceptorChain.length;\n\n while (i < len) {\n promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);\n }\n\n return promise;\n }\n\n getUri(config) {\n config = mergeConfig(this.defaults, config);\n const fullPath = buildFullPath(config.baseURL, config.url);\n return buildURL(fullPath, config.params, config.paramsSerializer);\n }\n}\n\n// Provide aliases for supported request methods\nutils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {\n /*eslint func-names:0*/\n Axios.prototype[method] = function(url, config) {\n return this.request(mergeConfig(config || {}, {\n method,\n url,\n data: (config || {}).data\n }));\n };\n});\n\nutils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {\n /*eslint func-names:0*/\n\n function generateHTTPMethod(isForm) {\n return function httpMethod(url, data, config) {\n return this.request(mergeConfig(config || {}, {\n method,\n headers: isForm ? {\n 'Content-Type': 'multipart/form-data'\n } : {},\n url,\n data\n }));\n };\n }\n\n Axios.prototype[method] = generateHTTPMethod();\n\n Axios.prototype[method + 'Form'] = generateHTTPMethod(true);\n});\n\nexport default Axios;\n", "'use strict';\n\nimport CanceledError from './CanceledError.js';\n\n/**\n * A `CancelToken` is an object that can be used to request cancellation of an operation.\n *\n * @param {Function} executor The executor function.\n *\n * @returns {CancelToken}\n */\nclass CancelToken {\n constructor(executor) {\n if (typeof executor !== 'function') {\n throw new TypeError('executor must be a function.');\n }\n\n let resolvePromise;\n\n this.promise = new Promise(function promiseExecutor(resolve) {\n resolvePromise = resolve;\n });\n\n const token = this;\n\n // eslint-disable-next-line func-names\n this.promise.then(cancel => {\n if (!token._listeners) return;\n\n let i = token._listeners.length;\n\n while (i-- > 0) {\n token._listeners[i](cancel);\n }\n token._listeners = null;\n });\n\n // eslint-disable-next-line func-names\n this.promise.then = onfulfilled => {\n let _resolve;\n // eslint-disable-next-line func-names\n const promise = new Promise(resolve => {\n token.subscribe(resolve);\n _resolve = resolve;\n }).then(onfulfilled);\n\n promise.cancel = function reject() {\n token.unsubscribe(_resolve);\n };\n\n return promise;\n };\n\n executor(function cancel(message, config, request) {\n if (token.reason) {\n // Cancellation has already been requested\n return;\n }\n\n token.reason = new CanceledError(message, config, request);\n resolvePromise(token.reason);\n });\n }\n\n /**\n * Throws a `CanceledError` if cancellation has been requested.\n */\n throwIfRequested() {\n if (this.reason) {\n throw this.reason;\n }\n }\n\n /**\n * Subscribe to the cancel signal\n */\n\n subscribe(listener) {\n if (this.reason) {\n listener(this.reason);\n return;\n }\n\n if (this._listeners) {\n this._listeners.push(listener);\n } else {\n this._listeners = [listener];\n }\n }\n\n /**\n * Unsubscribe from the cancel signal\n */\n\n unsubscribe(listener) {\n if (!this._listeners) {\n return;\n }\n const index = this._listeners.indexOf(listener);\n if (index !== -1) {\n this._listeners.splice(index, 1);\n }\n }\n\n toAbortSignal() {\n const controller = new AbortController();\n\n const abort = (err) => {\n controller.abort(err);\n };\n\n this.subscribe(abort);\n\n controller.signal.unsubscribe = () => this.unsubscribe(abort);\n\n return controller.signal;\n }\n\n /**\n * Returns an object that contains a new `CancelToken` and a function that, when called,\n * cancels the `CancelToken`.\n */\n static source() {\n let cancel;\n const token = new CancelToken(function executor(c) {\n cancel = c;\n });\n return {\n token,\n cancel\n };\n }\n}\n\nexport default CancelToken;\n", "'use strict';\n\n/**\n * Syntactic sugar for invoking a function and expanding an array for arguments.\n *\n * Common use case would be to use `Function.prototype.apply`.\n *\n * ```js\n * function f(x, y, z) {}\n * var args = [1, 2, 3];\n * f.apply(null, args);\n * ```\n *\n * With `spread` this example can be re-written.\n *\n * ```js\n * spread(function(x, y, z) {})([1, 2, 3]);\n * ```\n *\n * @param {Function} callback\n *\n * @returns {Function}\n */\nexport default function spread(callback) {\n return function wrap(arr) {\n return callback.apply(null, arr);\n };\n}\n", "'use strict';\n\nimport utils from './../utils.js';\n\n/**\n * Determines whether the payload is an error thrown by Axios\n *\n * @param {*} payload The value to test\n *\n * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false\n */\nexport default function isAxiosError(payload) {\n return utils.isObject(payload) && (payload.isAxiosError === true);\n}\n", "const HttpStatusCode = {\n Continue: 100,\n SwitchingProtocols: 101,\n Processing: 102,\n EarlyHints: 103,\n Ok: 200,\n Created: 201,\n Accepted: 202,\n NonAuthoritativeInformation: 203,\n NoContent: 204,\n ResetContent: 205,\n PartialContent: 206,\n MultiStatus: 207,\n AlreadyReported: 208,\n ImUsed: 226,\n MultipleChoices: 300,\n MovedPermanently: 301,\n Found: 302,\n SeeOther: 303,\n NotModified: 304,\n UseProxy: 305,\n Unused: 306,\n TemporaryRedirect: 307,\n PermanentRedirect: 308,\n BadRequest: 400,\n Unauthorized: 401,\n PaymentRequired: 402,\n Forbidden: 403,\n NotFound: 404,\n MethodNotAllowed: 405,\n NotAcceptable: 406,\n ProxyAuthenticationRequired: 407,\n RequestTimeout: 408,\n Conflict: 409,\n Gone: 410,\n LengthRequired: 411,\n PreconditionFailed: 412,\n PayloadTooLarge: 413,\n UriTooLong: 414,\n UnsupportedMediaType: 415,\n RangeNotSatisfiable: 416,\n ExpectationFailed: 417,\n ImATeapot: 418,\n MisdirectedRequest: 421,\n UnprocessableEntity: 422,\n Locked: 423,\n FailedDependency: 424,\n TooEarly: 425,\n UpgradeRequired: 426,\n PreconditionRequired: 428,\n TooManyRequests: 429,\n RequestHeaderFieldsTooLarge: 431,\n UnavailableForLegalReasons: 451,\n InternalServerError: 500,\n NotImplemented: 501,\n BadGateway: 502,\n ServiceUnavailable: 503,\n GatewayTimeout: 504,\n HttpVersionNotSupported: 505,\n VariantAlsoNegotiates: 506,\n InsufficientStorage: 507,\n LoopDetected: 508,\n NotExtended: 510,\n NetworkAuthenticationRequired: 511,\n};\n\nObject.entries(HttpStatusCode).forEach(([key, value]) => {\n HttpStatusCode[value] = key;\n});\n\nexport default HttpStatusCode;\n", "'use strict';\n\nimport utils from './utils.js';\nimport bind from './helpers/bind.js';\nimport Axios from './core/Axios.js';\nimport mergeConfig from './core/mergeConfig.js';\nimport defaults from './defaults/index.js';\nimport formDataToJSON from './helpers/formDataToJSON.js';\nimport CanceledError from './cancel/CanceledError.js';\nimport CancelToken from './cancel/CancelToken.js';\nimport isCancel from './cancel/isCancel.js';\nimport {VERSION} from './env/data.js';\nimport toFormData from './helpers/toFormData.js';\nimport AxiosError from './core/AxiosError.js';\nimport spread from './helpers/spread.js';\nimport isAxiosError from './helpers/isAxiosError.js';\nimport AxiosHeaders from \"./core/AxiosHeaders.js\";\nimport adapters from './adapters/adapters.js';\nimport HttpStatusCode from './helpers/HttpStatusCode.js';\n\n/**\n * Create an instance of Axios\n *\n * @param {Object} defaultConfig The default config for the instance\n *\n * @returns {Axios} A new instance of Axios\n */\nfunction createInstance(defaultConfig) {\n const context = new Axios(defaultConfig);\n const instance = bind(Axios.prototype.request, context);\n\n // Copy axios.prototype to instance\n utils.extend(instance, Axios.prototype, context, {allOwnKeys: true});\n\n // Copy context to instance\n utils.extend(instance, context, null, {allOwnKeys: true});\n\n // Factory for creating new instances\n instance.create = function create(instanceConfig) {\n return createInstance(mergeConfig(defaultConfig, instanceConfig));\n };\n\n return instance;\n}\n\n// Create the default instance to be exported\nconst axios = createInstance(defaults);\n\n// Expose Axios class to allow class inheritance\naxios.Axios = Axios;\n\n// Expose Cancel & CancelToken\naxios.CanceledError = CanceledError;\naxios.CancelToken = CancelToken;\naxios.isCancel = isCancel;\naxios.VERSION = VERSION;\naxios.toFormData = toFormData;\n\n// Expose AxiosError class\naxios.AxiosError = AxiosError;\n\n// alias for CanceledError for backward compatibility\naxios.Cancel = axios.CanceledError;\n\n// Expose all/spread\naxios.all = function all(promises) {\n return Promise.all(promises);\n};\n\naxios.spread = spread;\n\n// Expose isAxiosError\naxios.isAxiosError = isAxiosError;\n\n// Expose mergeConfig\naxios.mergeConfig = mergeConfig;\n\naxios.AxiosHeaders = AxiosHeaders;\n\naxios.formToJSON = thing => formDataToJSON(utils.isHTMLForm(thing) ? new FormData(thing) : thing);\n\naxios.getAdapter = adapters.getAdapter;\n\naxios.HttpStatusCode = HttpStatusCode;\n\naxios.default = axios;\n\n// this module should only have a default export\nexport default axios\n", "import axios from './lib/axios.js';\n\n// This module is intended to unwrap Axios default export as named.\n// Keep top-level export same with static properties\n// so that it can keep same with es module or cjs\nconst {\n Axios,\n AxiosError,\n CanceledError,\n isCancel,\n CancelToken,\n VERSION,\n all,\n Cancel,\n isAxiosError,\n spread,\n toFormData,\n AxiosHeaders,\n HttpStatusCode,\n formToJSON,\n getAdapter,\n mergeConfig\n} = axios;\n\nexport {\n axios as default,\n Axios,\n AxiosError,\n CanceledError,\n isCancel,\n CancelToken,\n VERSION,\n all,\n Cancel,\n isAxiosError,\n spread,\n toFormData,\n AxiosHeaders,\n HttpStatusCode,\n formToJSON,\n getAdapter,\n mergeConfig\n}\n", "import axios, {AxiosInstance, AxiosPromise} from \"axios\";\nimport {SingleTypeEventBus, TaggedLogger} from \"../utilities\";\nimport {\n ApiLotsRunningTimedStaggeredList,\n ApiPaginatedList,\n ApiRequestParams_detailsLevel,\n ApiRequestParams_lotsListBrowse,\n ApiRequestParams_pagination,\n ApiResource_Auction,\n ApiResource_Bid_TypeDef,\n ApiResource_ItemMediaFile_TypeDef,\n ApiResource_LotMetal,\n ApiResource_SiteSearchLot,\n ApiResource_WatchlistRunningLot,\n ApiResource_WebcastLot,\n ApiResourceDetailsLevelsEnum,\n} from \"../type_defs/api\";\nimport {WebcastAuctionConnectData_TypeDef} from \"../webcast\";\n\nexport const HEADER_BIDDER_TOKEN = 'Nextlot-Bidder-Token';\n\n\nconst _logger = TaggedLogger.get('FrontendApiAdapter');\n\n\nexport type OnHandlerFunction = (handlerFn: (args:HF_ARGS) => void) => () => void;\n\nexport default class FrontendApiAdapter {\n\n private readonly axiosInstance:AxiosInstance;\n private _bidderToken: string;\n\n private readonly authenticationChangeEventBus: SingleTypeEventBus;\n public onAuthenticationStateChanged: OnHandlerFunction;\n\n private readonly responseSuccessEventBus: SingleTypeEventBus<{ headers:{} }>;\n public onResponseSuccess: OnHandlerFunction<{headers:{}}>;\n\n\n constructor(config:{ frontendApiBaseUrl:string, siteId: number }) {\n _logger.info('.constructor() config:', config);\n\n this.axiosInstance = axios.create({\n baseURL: `${config.frontendApiBaseUrl}/sites/${config.siteId}`,\n timeout: (1_000 * 30), // 30 seconds\n headers: {\n // default headers here\n }\n });\n\n this.authenticationChangeEventBus = new SingleTypeEventBus();\n this.responseSuccessEventBus = new SingleTypeEventBus();\n\n // short syntax to alias a function\n this.onAuthenticationStateChanged = this.authenticationChangeEventBus.on;\n this.onResponseSuccess = this.responseSuccessEventBus.on;\n\n\n // REQUEST interceptors\n this.axiosInstance.interceptors.request.use(\n (axiosRequestConfig) => {\n // _logger.debug('request: ', axiosRequestConfig);\n return axiosRequestConfig;\n },\n (error) => {\n return Promise.reject(error);\n });\n\n\n // RESPONSE interceptors\n this.axiosInstance.interceptors.response.use(\n // on success handling\n (axiosResponse) => {\n // _logger.debug('response SUCCESS: ', axiosResponse.request.responseURL, axiosResponse.data);\n this.responseSuccessEventBus.emit({ headers: axiosResponse.headers });\n return axiosResponse;\n },\n\n\n (error) => {\n _logger.debug(`response ERROR for request: ` + error.request, error.isAxiosError ? error.toJSON() : JSON.stringify(error));\n\n // handle authentication errors, usually caused by an invalid token\n if (error.response?.status === 401) {\n // remove the bidder token for further use\n this._setBidderTokenHeader(null);\n }\n\n return Promise.reject(error);\n });\n\n\n if (__DEV__) {\n ((window || {}) as any)._dev_FrontendApiService_instance = this;\n }\n }\n\n // for dev/debug purpose\n get _axiosInstance():AxiosInstance {\n return this.axiosInstance;\n }\n\n\n\n async asyncRemoteVerifyBidderToken(setBidderToken:string|null):Promise {\n if (setBidderToken || setBidderToken === null) {\n this._setBidderTokenHeader(setBidderToken, true);\n }\n if (! this._bidderToken) {\n // if no token is set, then don't even trigger the remote request\n return false;\n }\n try {\n // NOTE! if this fails with error status 401, it will trigger the removal of the header token from axiosInstance\n await this.getAccountMe();\n\n _logger.info('.asyncRemoteVerifyBidderToken: token VALID');\n return true;\n }\n catch (ex) {\n _logger.warn('.asyncRemoteVerifyBidderToken: FAILED to `GET /account/me`', ex);\n return false;\n }\n }\n\n\n private _setBidderTokenHeader(token:string|null, skipEmitEvent?:true) {\n if (token) {\n this._bidderToken = token;\n this.axiosInstance.defaults.headers[HEADER_BIDDER_TOKEN] = token;\n _logger.info('._setBidderTokenHeader: token PRESENT');\n }\n else {\n this._bidderToken = null;\n this.axiosInstance.defaults.headers[HEADER_BIDDER_TOKEN] = undefined;\n delete this.axiosInstance.defaults.headers[HEADER_BIDDER_TOKEN];\n _logger.info('._setBidderTokenHeader: token NULL');\n }\n\n if (! skipEmitEvent) {\n this.authenticationChangeEventBus.emit(!!this._bidderToken);\n }\n }\n\n\n get bidderToken():string|null {\n return this._bidderToken;\n }\n\n\n getAccountMe():AxiosPromise<{id:number|null, email?:string}> {\n return this.axiosInstance.get('/account/me');\n };\n\n\n\n getAuctions(params:ApiRequestParams_detailsLevel & { completes_at?:-1|1 }):AxiosPromise> {\n return this.axiosInstance.get('/auctions', { params });\n };\n\n getAuctionDetails(auctionId:number, params:ApiRequestParams_detailsLevel):AxiosPromise {\n return this.axiosInstance.get(`/auctions/${auctionId}`, { params })\n }\n\n putAuctionBiddingWarrant(auctionId:number, expectedState:string, isNotificationSmsAuctionTimelineEnabled:boolean):AxiosPromise<{current_state:string}> {\n return this.axiosInstance.put(`/auctions/${auctionId}/warrant`, { expected_state: expectedState, notification_sms_auction_timeline_enabled: isNotificationSmsAuctionTimelineEnabled });\n }\n\n putAuctionTimelineNotification(auctionId:number, isNotificationSmsAuctionTimelineEnabled:boolean) {\n return this.axiosInstance.put(`/auctions/${auctionId}/auction_timeline_notifications`, { notification_sms_auction_timeline_enabled: isNotificationSmsAuctionTimelineEnabled });\n }\n\n getAuctionLots(auctionId:number, params:ApiRequestParams_lotsListBrowse = {}):AxiosPromise> {\n return this.axiosInstance.get(`/auctions/${auctionId}/lots`, { params });\n };\n\n getWatchlistLotsRunning(params:ApiRequestParams_pagination = {}):AxiosPromise> {\n return this.axiosInstance.get(`/watchlist/lots/running`, { params });\n };\n\n getSearchLots(params:ApiRequestParams_pagination = {}):AxiosPromise> {\n return this.axiosInstance.get(`/search/lots`, { params: { ... params } });\n };\n\n\n postAuctionWebcastEnter(auctionId:number, viewerId:number = null):AxiosPromise<{ connect_data: WebcastAuctionConnectData_TypeDef }> {\n const data:{ viewer_id?:number } = {};\n if (viewerId) {\n data.viewer_id = viewerId;\n }\n return this.axiosInstance.post(`/auctions/${auctionId}/webcast_enter`, data);\n };\n\n getAuctionWebcastLots(auctionId:number, params:ApiRequestParams_pagination = {}):AxiosPromise> {\n return this.axiosInstance.get(`/auctions/${auctionId}/webcast_lots`, { params });\n };\n\n getAuctionRunningLotsTimedStaggered(auctionId:number, refTimestamp?:number, cursorTimestamp?:number):AxiosPromise {\n const params = cursorTimestamp > 1 ? { cursor_timestamp: cursorTimestamp, ref_timestamp: refTimestamp } : {};\n return this.axiosInstance.get(`/auctions/${auctionId}/lots/running_timed_staggered`, { params });\n };\n\n\n\n getAuctionLot(auctionId:number, lotId:number, detailsLevel:ApiResourceDetailsLevelsEnum = ApiResourceDetailsLevelsEnum.metal):AxiosPromise {\n return this.axiosInstance.get(`/auctions/${auctionId}/lots/${lotId}`, { params: { details_level: detailsLevel }});\n }\n\n\n getAuctionLotItemMediaFiles(auctionId:number, lotId:number):AxiosPromise> {\n return this.axiosInstance.get(`/auctions/${auctionId}/lots/${lotId}/item_media_files`);\n }\n\n\n postAuctionLotBidOnline(auctionId:number, lotId:number, maxBidAmountCents:number, raise:boolean):AxiosPromise {\n return this.axiosInstance.post(`/auctions/${auctionId}/lots/${lotId}/bids/online`, { max_amount_cents: maxBidAmountCents, raise: raise });\n }\n\n getAuctionLotBids(auctionId:number, lotId:number):AxiosPromise> {\n return this.axiosInstance.get(`/auctions/${auctionId}/lots/${lotId}/bids`);\n }\n\n postAuctionLotInterest(auctionId:number, lotId:number, setIsWatched:boolean):AxiosPromise {\n return this.axiosInstance.put(`/auctions/${auctionId}/lots/${lotId}/interest`, { watched: setIsWatched });\n }\n\n}\n\n", "import type {DateTime} from 'luxon';\nimport {Auction_ModelTypeDef} from \"../type_defs/model\";\n\n\nexport function buildAuctionTimelineLabels(auction:Auction_ModelTypeDef, dateTimeFormatFunc:(dateTime:DateTime)=>string):[string, string?] {\n // Completed auctions\n if (auction.timelineState.isCompleted) {\n return [`Closed ${dateTimeFormatFunc(auction.completesAt)}`];\n }\n\n // Upcoming auctions\n else if (auction.timelineState.isUpcoming) {\n if (auction.auctionType.isTimed) {\n return [`Starts on ${dateTimeFormatFunc(auction.startsAt)}`,\n `Lots start closing on ${dateTimeFormatFunc(auction.closingStartsAt)}`];\n\n }\n else if (auction.auctionType.isSealed) {\n return [`Starts on ${dateTimeFormatFunc(auction.startsAt)}`,\n `Closing on ${dateTimeFormatFunc(auction.closingStartsAt)}`];\n\n }\n else if (auction.auctionType.isWebcast) {\n return [`Webcast starts on ${dateTimeFormatFunc(auction.startsAt)}`];\n\n }\n else if (auction.auctionType.isCombinedAny) {\n return [\n `${auction.auctionType.isCombinedAbsentee ? 'Absentee bidding' : 'Pre-bidding'} opens on ${dateTimeFormatFunc(auction.startsAt)}`,\n `Webcast starts on ${dateTimeFormatFunc(auction.webcastStartsAt)}`\n ];\n }\n }\n\n // Running auctions && Running extended\n else if (auction.timelineState.isLive) {\n if (auction.auctionType.isTimed) {\n return [`First lot closing on ${dateTimeFormatFunc(auction.closingStartsAt)}`];\n\n }\n else if (auction.auctionType.isSealed) {\n return [`Closing on ${dateTimeFormatFunc(auction.closingStartsAt)}`];\n\n }\n else if (auction.auctionType.isWebcast) {\n if (auction.webcastIsPrepared) {\n return ['Live now'];\n }\n else {\n return [`Webcast will start soon (scheduled ${dateTimeFormatFunc(auction.webcastStartsAt)})`];\n }\n }\n else if (auction.auctionType.isCombinedAny) {\n return [\n `${auction.auctionType.isCombinedAbsentee ? 'Absentee bidding' : 'Pre-bidding'} ${auction.currentSegmentType.isOnline ? 'closes' : 'closed'} on ${dateTimeFormatFunc(auction.closingStartsAt)}`,\n auction.currentSegmentType.isWebcast\n ? (auction.webcastIsPrepared ? 'Webcast is live now' : 'Webcast will start soon')\n : `Webcast starts on ${dateTimeFormatFunc(auction.webcastStartsAt)}`];\n\n }\n }\n\n // Stalled auctions\n else { // isStalled\n if (auction.auctionType.isCombinedAny) {\n return [\n `${auction.auctionType.isCombinedAbsentee ? 'Absentee bidding' : 'Pre-bidding'} closed on ${dateTimeFormatFunc(auction.closingStartsAt)}`,\n `Webcast starts on ${dateTimeFormatFunc(auction.webcastStartsAt)}`\n ];\n }\n else if(auction.auctionType.hasWebcastBidding) {\n return [`Webcast starts on ${dateTimeFormatFunc(auction.webcastStartsAt)}`];\n }\n else {\n return ['Auction paused'];\n }\n }\n}\n", "import {DateTime, Duration} from \"luxon\";\n\n\n// const LOCALE = Intl.NumberFormat().resolvedOptions().locale;\n\nexport function formatDateTime(dateTime:DateTime, formatString:string = DATETIME_FORMAT_STRINGS.AUCTION_CARD) {\n return dateTime ? dateTime.toFormat(formatString) : ''\n}\n\n\nexport function formatBidExtensionDurationSeconds(seconds:number|undefined):string {\n if (! seconds) {\n return '';\n }\n\n const minutes = Math.floor(seconds / 60);\n const secondsReminder = seconds % 60;\n\n return [\n (minutes > 0 ? `${minutes} min` : null),\n (secondsReminder > 0 ? `${secondsReminder} s` : null)\n ].filter(v => v).join(' ');\n}\n\n\nexport enum DATETIME_FORMAT_STRINGS {\n AUCTION_CARD = \"LLL d, y 'at' h:mma ZZZZ\",\n AUCTION_HEADER = \"LLL d, y 'at' h:mma ZZZZ\",\n LOT_CARD_WITH_WEEKDAY = \"ccc, LLL d\",\n LOT_CARD_TIME_SIMPLE = \"h:mma ZZZZ\",\n LOT_CARD_SEARCH = \"LLL d y 'at' h:mma ZZZZ\",\n}\n\n\n\nexport function formatDurationAsHumanString(duration:Duration):string {\n const durObj = duration.shiftTo('hours', 'minutes', 'seconds').toObject();\n durObj.seconds = Math.floor(durObj.seconds); // use `floor` to account for computational and network times\n const strHours = durObj.hours !== 0 ? `${Math.abs(durObj.hours)}h` : null;\n const strMinutes = (strHours || durObj.minutes !== 0) ? `${Math.abs(durObj.minutes)}m` : null;\n const strSeconds = `${Math.abs(durObj.seconds)}s`;\n return [strHours, strMinutes, strSeconds].filter(v => v).join(' ');\n}\n", "\nexport { buildAuctionTimelineLabels} from \"./DataModelHelpers\";\n\nexport { formatBidExtensionDurationSeconds, formatDateTime, formatDurationAsHumanString, DATETIME_FORMAT_STRINGS } from \"./DateTimeHelpers\";\n", "import {DateTime} from 'luxon';\nimport StaticModelsAndConstants from \"../StaticModelsAndConstants\";\nimport {\n ApiResource_Auction,\n ApiResource_Bid_TypeDef,\n ApiResource_ItemMediaFile_TypeDef,\n ApiResource_LotMetal,\n ApiResourceDetailsLevelsEnum\n} from \"../type_defs/api\";\nimport {Auction_ModelTypeDef, Bid_ModelTypeDef, LotItemMediaFile_ModelTypeDef, LotMetal_ModelTypeDef} from \"../type_defs/model\";\nimport {formatBidExtensionDurationSeconds} from \"../helpers\";\n\n\nconst ApiDtoConvertors = {\n\n convertAuction: (dto:ApiResource_Auction, meta?:{ _detailsLevel?:ApiResourceDetailsLevelsEnum, _class?:string, }):Auction_ModelTypeDef => {\n return {\n _class: dto._class,\n ... meta,\n\n id: dto.id,\n siteId: dto.site_id,\n\n auctionType: StaticModelsAndConstants.AuctionTypes.getById(dto.auction_type_id),\n\n name: dto.name,\n urlThumbImage: dto.url_thumb_image,\n\n locationInfo: dto.location_info_text,\n summary: dto.summary_html,\n viewingInfo: dto.viewing_info_text,\n detailsPageHtml: dto.details_page_html,\n\n internetBuyerPremiumDisplayText: dto.internet_buyer_premium_display_text,\n onsiteBuyerPremiumDisplayText: dto.onsite_buyer_premium_display_text,\n\n auctionTimezoneName: dto.auction_timezone_name,\n\n startsAt: DateTime.fromSeconds(dto.starts_at).setZone(dto.auction_timezone_name),\n webcastStartsAt: dto.webcast_starts_at && DateTime.fromSeconds(dto.webcast_starts_at).setZone(dto.auction_timezone_name),\n closingStartsAt: DateTime.fromSeconds(dto.closing_starts_at).setZone(dto.auction_timezone_name),\n closingEndsAt: DateTime.fromSeconds(dto.closing_ends_at).setZone(dto.auction_timezone_name),\n completesAt: DateTime.fromSeconds(dto.completes_at).setZone(dto.auction_timezone_name),\n isCompleted: dto.is_completed,\n\n timelineState: StaticModelsAndConstants.AuctionTimelineStates.getById(dto.timeline_state_id),\n currentSegmentType: StaticModelsAndConstants.AuctionSegmentTypes.getByCode(dto.current_segment_type_code),\n\n currencyCode: dto.currency_code,\n\n lotsCount: dto.lots_count,\n\n biddingApprovalMode: StaticModelsAndConstants.AuctionBiddingApprovalModes.getByCode(dto.bidding_approval_mode_code),\n\n bidRequestNoteText: dto.bid_request_note_text,\n\n bidIncrementsTable: dto.bid_increments_table,\n\n myBiddingWarrantState: StaticModelsAndConstants.BiddingWarrantStates.getByCode(dto.my_bidding_warrant_state_code),\n notificationSmsAuctionTimelineEnabled: dto.notification_sms_auction_timeline_enabled,\n\n timedJumpBidsAllowed: dto.timed_jump_bids_allowed,\n\n timedBiddingExtensionSeconds: dto.timed_bidding_extension,\n timedBiddingExtensionDurationDisplayText: formatBidExtensionDurationSeconds(dto.timed_bidding_extension),\n\n timedLotsStaggeringGroupSize: dto.timed_lots_staggering_ruleset ? dto.timed_lots_staggering_ruleset.s1_group_size : undefined,\n timedLotsStaggeringOffsetSeconds: dto.timed_lots_staggering_ruleset ? dto.timed_lots_staggering_ruleset.s1_time_offset_seconds : undefined,\n\n webcastIsPrepared: dto.webcast_is_prepared,\n\n enterWebcastScreenAppLinkUrl: dto.enter_webcast_screen_applink_url,\n\n } as Auction_ModelTypeDef;\n },\n\n\n convertLot: (dto:T_ApiLot, meta?:{ _detailsLevel?:ApiResourceDetailsLevelsEnum, _class?:string }):T_ModelLot => {\n\n return {\n _class: dto._class,\n ... meta,\n\n id: dto.id,\n createdAt: DateTime.fromSeconds(dto.created_at) as DateTime,\n\n auctionId: dto.auction_id,\n\n number: dto.number,\n numberSort: dto.number_sort,\n\n customSort: dto.custom_sort,\n\n name: dto.name,\n quantity: dto.quantity,\n description: dto.description_html,\n focalMediaFileThumbImageUrl: dto.focal_media_file_url_thumb_image,\n videoUrlThumbImage: dto.video_url_thumb_image,\n videoUrl: dto.video_url,\n\n updatedAt: dto.updated_at ? DateTime.fromSeconds(dto.updated_at).setZone(dto.auction_timezone_name) : undefined,\n closesAt: DateTime.fromSeconds(dto.closes_at).setZone(dto.auction_timezone_name),\n completesAt: DateTime.fromSeconds(dto.completes_at).setZone(dto.auction_timezone_name) as DateTime,\n isCompleted: dto.is_completed,\n hasRound: dto.has_round,\n\n linkedLotsGroupId: dto.linked_lots_group_id,\n\n\n bidsCount: dto.bids_count,\n\n leadingBidAmountCents: dto.leading_bid_amount_cents,\n\n leadingBidBidderNumber: dto.leading_bid_bidder_number,\n leadingBidBidderLabel: dto.leading_bid_bidder_label,\n leadingBidBidderDisplayText: buildBidBidderDisplayText(dto.leading_bid_bidder_number, dto.leading_bid_bidder_label),\n\n myBidIsLeadingBid: dto.my_bid_is_leading_bid,\n\n // buy_now_price_cents: dto.buy_now_price_cents,\n reservePriceStatusCode: dto.reserve_price_status_code,\n\n startingBidAmountCents: dto.starting_bid_amount_cents,\n askingBidAmountCents: dto.asking_bid_amount_cents,\n\n myMaxBidAmountCents: dto.my_max_bid_amount_cents,\n myBidExistsInHistory: dto.my_bid_exists_in_history,\n\n myWatched: dto.my_watched,\n } as T_ModelLot;\n },\n\n\n\n\n\n convertItemMediaFile: (dto:ApiResource_ItemMediaFile_TypeDef, extraFields?:Partial & Pick):LotItemMediaFile_ModelTypeDef => {\n return {\n id: dto.id,\n\n sortIdx: dto.sort_idx,\n\n mediaType: StaticModelsAndConstants.ItemMediaTypes.getById(dto.media_type_id),\n\n url: dto.url,\n urlThumbImage: dto.url_thumb_image,\n urlHighDef: dto.url_high_def,\n\n ... extraFields\n }\n },\n\n\n\n\n convertBid: (dto:ApiResource_Bid_TypeDef, auctionTimezoneName:string):Bid_ModelTypeDef => {\n return {\n id: dto.id,\n\n recipientId: dto.recipient_id,\n auctionId: dto.auction_id,\n\n amountCents: dto.amount_cents,\n createdAt: DateTime.fromSeconds(dto.created_at).setZone(auctionTimezoneName),\n placedAt: DateTime.fromSeconds(dto.placed_at).setZone(auctionTimezoneName),\n\n bidderNumber: dto.bidder_number,\n bidderLabel: dto.bidder_label,\n bidderDisplayText: buildBidBidderDisplayText(dto.bidder_number, dto.bidder_label),\n\n isAuto: dto.is_auto,\n isOverridden: dto.is_overridden,\n }\n },\n}\n\nexport default ApiDtoConvertors;\n\n\nfunction buildBidBidderDisplayText(bidderNumber:string|undefined|null, bidderLabel:string|undefined):string {\n if (!bidderNumber) {\n return ''; // should NOT happen\n }\n\n if (bidderNumber === '0' || bidderNumber.startsWith('#')) {\n return bidderLabel as string;\n }\n\n if (bidderLabel) {\n return `${bidderNumber} (${bidderLabel})`;\n }\n else {\n return `${bidderNumber}`;\n }\n}\n\n", "import {TaggedLogger} from \"../utilities\";\nimport FrontendApiAdapter, {OnHandlerFunction} from \"./FrontendApiAdapter\";\nimport {\n ApiRequestParams_auctionsList,\n ApiRequestParams_lotsListBrowse,\n ApiRequestParams_lotsSearch,\n ApiRequestParams_pagination,\n ApiResource_CatalogLot,\n ApiResource_LotMetal,\n ApiResource_RunningTimedLot,\n ApiResource_SiteSearchLot,\n ApiResource_WatchlistRunningLot,\n ApiResourceDetailsLevelsEnum\n} from \"../type_defs/api\";\nimport {\n Auction_ModelTypeDef,\n Bid_ModelTypeDef,\n CatalogLot_ModelTypeDef,\n LotItemMediaFile_ModelTypeDef,\n LotMetal_ModelTypeDef,\n ListingBrowserParams,\n LotsPaginatedList_TypeDef,\n LotsRunningTimedStaggeredList_TypeDef,\n PaginatedList_TypeDef,\n RunningCatalogLot_ModelTypeDef,\n WatchlistRunningLot_ModelTypeDef\n} from \"../type_defs/model\";\nimport ApiDtoConvertors from \"./ApiDtoConvertors\";\nimport {LotDetails} from \"../webcast/data/data_types_definitions\";\nimport {WebcastAuctionConnectData_TypeDef} from \"../webcast\";\n\n\nconst _logger = TaggedLogger.get('AppRemoteDataHandler');\n\n\nexport class AppRemoteDataHandler {\n\n private readonly _frontendApi:FrontendApiAdapter;\n public readonly onAuthenticationStateChanged: OnHandlerFunction;\n public readonly onResponseSuccess: OnHandlerFunction<{ headers: {} }>;\n\n constructor(siteConfig:{ siteId:number, frontendApiBaseUrl:string }) {\n this._frontendApi = new FrontendApiAdapter({\n siteId: siteConfig.siteId,\n frontendApiBaseUrl: siteConfig.frontendApiBaseUrl,\n });\n\n this.onAuthenticationStateChanged = this._frontendApi.onAuthenticationStateChanged;\n this.onResponseSuccess = this._frontendApi.onResponseSuccess;\n }\n\n get _frontendApi_do_not_use():FrontendApiAdapter {\n return this._frontendApi;\n }\n\n\n setAndAsyncRemoteVerifyBidderToken(setBidderToken:string|null):Promise {\n return this._frontendApi.asyncRemoteVerifyBidderToken(setBidderToken);\n }\n\n\n\n async submitAcceptSaleTerms(auctionId: number, expectedState: string, isNotificationSmsAuctionTimelineEnabled: boolean):Promise<{\n currentState: string\n }> {\n try {\n const response = await this._frontendApi.putAuctionBiddingWarrant(auctionId, expectedState, isNotificationSmsAuctionTimelineEnabled);\n return { currentState: response.data.current_state };\n }\n catch (ex) {\n handleAxiosError(ex);\n }\n }\n\n\n async updateAuctionTimelineNotification(auctionId:number, isNotificationSmsAuctionTimelineEnabled:boolean):Promise<{isNotificationSmsAuctionTimelineEnabled:boolean}> {\n // _logger.debug('.updateAuctionTimelineNotification: auction: ', auctionId, 'updateTo: ', isNotificationSmsAuctionTimelineEnabled);\n try {\n const response = await this._frontendApi.putAuctionTimelineNotification(auctionId, isNotificationSmsAuctionTimelineEnabled);\n return {isNotificationSmsAuctionTimelineEnabled: response.data.notification_sms_auction_timeline_enabled};\n }\n catch (ex) {\n handleAxiosError(ex);\n }\n }\n\n\n async submitPlaceBid(auctionId: number, lotId:number, maxBidAmount:number, raiseBid:boolean) {\n _logger.debug('.submitPlaceBid: lot:', lotId, ' amount:', maxBidAmount);\n try {\n await this._frontendApi.postAuctionLotBidOnline(auctionId, lotId, maxBidAmount, raiseBid);\n return {};\n }\n catch (ex) {\n handleAxiosError(ex);\n }\n }\n\n\n async submitLotInterest(auctionId: number, lotId: number, setIsWatched:boolean) {\n _logger.debug('.submitLotInterest: lot:', lotId, ' setIsWatched:', setIsWatched);\n try {\n const response = await this._frontendApi.postAuctionLotInterest(auctionId, lotId, setIsWatched);\n return response.data;\n }\n catch (ex) {\n handleAxiosError(ex);\n }\n }\n\n\n\n\n async fetchAuctionsList(params?:ListingBrowserParams & { completesAt?: -1|1 }):Promise> {\n try {\n const apiParams:ApiRequestParams_auctionsList = {\n page_number: params?.pageNumber,\n page_size: params?.pageSize,\n details_level: params?.entityDetailsLevel || ApiResourceDetailsLevelsEnum.minimal,\n };\n if (params?.completesAt) {\n apiParams.completes_at = params.completesAt;\n }\n\n const axiosResponse = await this._frontendApi.getAuctions(apiParams);\n\n return {\n list: axiosResponse.data.data.map((dto) => ApiDtoConvertors.convertAuction(dto, { _detailsLevel: apiParams.details_level })),\n totalCount: axiosResponse.data.total_count,\n pageNumber: axiosResponse.data.page_number,\n pageSize: axiosResponse.data.page_size,\n pagesCount: axiosResponse.data.pages_count,\n };\n\n }\n catch (ex) {\n handleAxiosError(ex);\n }\n }\n\n async fetchAuction(auctionId:number, detailsLevel?:ApiResourceDetailsLevelsEnum):Promise {\n try {\n const axiosResponse = await this._frontendApi.getAuctionDetails(auctionId, { details_level: detailsLevel });\n return ApiDtoConvertors.convertAuction(axiosResponse.data, { _detailsLevel: detailsLevel } );\n }\n catch (ex) {\n handleAxiosError(ex);\n }\n }\n\n\n async submitAuctionWebcastEnter(auctionId:number, viewerId:number = null):Promise<{ connectData:WebcastAuctionConnectData_TypeDef }> {\n try {\n const axiosResponse = await this._frontendApi.postAuctionWebcastEnter(auctionId, viewerId);\n return {\n connectData: axiosResponse.data?.connect_data\n };\n }\n catch (ex) {\n handleAxiosError(ex);\n }\n }\n\n\n async fetchAuctionLotsListBrowsable(auctionId:number, params?:ListingBrowserParams):Promise> {\n try {\n const apiParams:ApiRequestParams_lotsListBrowse = {\n page_number: params?.pageNumber,\n page_size: params?.pageSize,\n sorting_criteria: params?.sortingCriteria,\n filters: params?.filters,\n details_level: params?.entityDetailsLevel,\n };\n\n const axiosResponse = await this._frontendApi.getAuctionLots(auctionId, apiParams);\n const responseData = axiosResponse.data;\n\n return {\n list: responseData.data.map((dto) => ApiDtoConvertors.convertLot(dto, { _detailsLevel: apiParams.details_level })),\n totalCount: responseData.total_count,\n pageNumber: responseData.page_number,\n pageSize: responseData.page_size,\n pagesCount: responseData.pages_count,\n sortingCriteria: responseData.extra.sorting_criteria,\n filters: responseData.extra.filters,\n };\n }\n catch (ex) {\n handleAxiosError(ex);\n }\n }\n\n\n\n\n async fetchAuctionLotsRunningTimedStaggeredPaginatedList(auctionId:number, refTimestamp?:number|null, cursorTimestamp?:number):Promise {\n try {\n\n const axiosResponse = await this._frontendApi.getAuctionRunningLotsTimedStaggered(auctionId, refTimestamp, cursorTimestamp);\n const responseData = axiosResponse.data;\n\n return {\n list: responseData.data.map((dto) => ApiDtoConvertors.convertLot(dto)),\n totalCount: responseData.total_count,\n windowCount: responseData.window_count,\n refTimestamp: responseData.ref_timestamp,\n cursorTimestamp: responseData.cursor_timestamp,\n nextCursorTimestamp: responseData.next_cursor_timestamp,\n };\n\n }\n catch (ex) {\n handleAxiosError(ex);\n }\n }\n\n\n\n async fetchAuctionWebcastLots(auctionId:number):Promise> {\n const fetchPage = async (pageNo:number) => {\n const axiosResponse = await this._frontendApi.getAuctionWebcastLots(auctionId, { page_number: pageNo });\n return axiosResponse.data;\n }\n\n try {\n let pageNo = 1;\n const responseData = await fetchPage(pageNo);\n let responseDataLots = responseData.data;\n\n while (pageNo < responseData.pages_count) {\n pageNo += 1;\n const responseData = await fetchPage(pageNo);\n // merge the lots arrays\n responseDataLots = responseDataLots.concat(responseData.data);\n }\n\n return responseDataLots.map((apiLot) => ({\n id: apiLot.id,\n\n number: apiLot.number,\n\n name: apiLot.name,\n description: apiLot.description_html,\n\n images: apiLot.images.map((apiLotImage) => ({\n smUrl: apiLotImage.url_thumb,\n mdUrl: apiLotImage.url_thumb,\n fsUrl: apiLotImage.url,\n })),\n\n defaultImageSmUrl: apiLot.images[0].url_thumb,\n\n videoUrl: apiLot.video_url\n }));\n }\n catch (ex) {\n handleAxiosError(ex)\n }\n }\n\n async fetchWatchlistLotsListBrowsable(params:{ pageNumber:number, refTimestamp?:number }):Promise> {\n try {\n const apiParams:ApiRequestParams_pagination & { ref_timestamp?: number } = {\n page_number: params?.pageNumber || 1,\n page_size: 36, // default 36 items\n ref_timestamp: params?.refTimestamp,\n };\n\n const axiosResponse = await this._frontendApi.getWatchlistLotsRunning(apiParams);\n const responseData = axiosResponse.data;\n\n return {\n list: responseData.data.map((dto) => {\n const lot = ApiDtoConvertors.convertLot(dto);\n lot.auction = ApiDtoConvertors.convertAuction(dto.auction);\n return lot;\n }),\n totalCount: responseData.total_count,\n pageNumber: responseData.page_number,\n pageSize: responseData.page_size,\n pagesCount: responseData.pages_count,\n };\n }\n catch (ex) {\n handleAxiosError(ex);\n }\n }\n\n\n async fetchSearchLotsListBrowsable(params:ListingBrowserParams):Promise> {\n try {\n const apiParams:ApiRequestParams_lotsSearch = {\n page_number: params?.pageNumber || 1,\n filters: params?.filters,\n sorting_criteria: params?.sortingCriteria,\n };\n\n const axiosResponse = await this._frontendApi.getSearchLots(apiParams);\n const responseData = axiosResponse.data;\n\n return {\n list: responseData.data.map((dto) => {\n const lot = ApiDtoConvertors.convertLot(dto);\n lot.auction = ApiDtoConvertors.convertAuction(dto.auction);\n return lot;\n }),\n totalCount: responseData.total_count,\n pageNumber: responseData.page_number,\n pageSize: responseData.page_size,\n pagesCount: responseData.pages_count,\n };\n }\n catch (ex) {\n handleAxiosError(ex);\n }\n }\n\n async fetchAuctionLot(auctionId:number, lotId:number, detailsLevel:ApiResourceDetailsLevelsEnum = ApiResourceDetailsLevelsEnum.metal):Promise {\n try {\n const axiosResponse = await this._frontendApi.getAuctionLot(auctionId, lotId, detailsLevel);\n const responseData = axiosResponse.data;\n return ApiDtoConvertors.convertLot(responseData, { _class: responseData._class });\n }\n catch (ex) {\n handleAxiosError(ex);\n }\n }\n\n\n\n async fetchAuctionLotItemMediaFilesList(auctionId:number, lotId:number):Promise> {\n try {\n const response = await this._frontendApi.getAuctionLotItemMediaFiles(auctionId, lotId);\n const responseData = response.data;\n\n return {\n list: responseData.data.map((dto) => ApiDtoConvertors.convertItemMediaFile(dto, { auctionId: auctionId, lotId: lotId })),\n totalCount: responseData.data.length,\n pageNumber: 1,\n pagesCount: 1,\n pageSize: 100,\n };\n }\n catch (ex) {\n handleAxiosError(ex);\n }\n }\n\n\n async fetchAuctionLotBidsList(auctionId:number, lotId:number):Promise> {\n try {\n const response = await this._frontendApi.getAuctionLotBids(auctionId, lotId);\n const responseData = response.data;\n\n return {\n list: responseData.data?.map((dto) => ApiDtoConvertors.convertBid(dto, responseData.auction_timezone_name)),\n totalCount: responseData.total_count,\n pageNumber: 1,\n pagesCount: 1,\n pageSize: 500, // default server side\n };\n }\n catch (ex) {\n handleAxiosError(ex);\n }\n }\n\n\n}\n\n\n\n\n/**\n * @throws AxiosError\n */\nfunction handleAxiosError(ex):never {\n _logger.warn('AxiosError: ', ex);\n\n if (ex.response) {\n // status is 4xx or 5xx\n throw ex;\n }\n else if (ex.request) {\n // no response received from server (usually timeout)\n throw new Error('Request timed out');\n }\n else {\n throw ex; // any other error, like error setting up the request\n }\n}\n", "import URI from \"urijs\";\nimport type {LotDetails, PMAuctionDataSnapshot, PMAuctionDataSyncStatusChanged, PMRoundStopped, WBSWebsocketMessage} from \"../data/data_types_definitions\";\nimport {TaggedLogger} from '../../utilities';\nimport {\n ACTION_TYPES,\n ActionBuilder,\n ActionsCreators,\n ChannelEnum,\n type CurrentRoundCloseActionPayloadType,\n type CurrentRoundStopActionPayloadType,\n WbsCommStatesEnum,\n WbsNetworkStatusConnectionStateEnum\n} from \"../redux/actions\";\n\nimport {RoundStopTypeEnum} from \"../data/WebcastDataDomain\";\nimport DataStore, {type ReduxStateType} from \"./DataStore\";\nimport type {ReduxActiveWebcastSubStateType} from \"../redux/reducerActiveWebcast\";\nimport type {Store} from \"redux\";\nimport {getMoneyHelperForCurrencyCode} from \"../../services/MoneyHelper\";\nimport {AppRemoteDataHandler} from \"../../services/AppRemoteDataHandler\";\nimport {WebcastScreenTypeCodesEnum} from \"../../StaticModelsAndConstants\";\n\n\ntype WebcastAuctionHandlerControllerType = {\n sendAuctionDataSyncApply(): void,\n\n sendBidPlace(roundId: string, value: number): void,\n sendChoiceLotsSelection(roundId: string, lotsIds:Array):void,\n\n sendWebcastStatusChange(statusData: any): void,\n sendRoundCreate(roundType: number, lotsIds: Array): void,\n sendRoundStop(roundId: string, stopType: number): void,\n\n sendAskingBidUpdate(roundId: string, askingBidValue: number, bidIncrement?: number): void,\n sendBidRevise(roundId: string, reviseType: number, bidValue: number): void,\n sendPreBidPlace(roundId: string, bidderUserId:number, value: number): void,\n\n sendChoiceLotsAssignment(roundId: string, lotsIds:Array, usersIds:Array, nextRoundType:number): void,\n\n sendLotsPass(lotsIds: Array): void,\n\n sendChatMessage(roomId: number, body: string): void,\n\n openChatRoomAndMarkAsRead(roomId: number): void,\n closeChatRoom(roomId: number): void,\n\n sendStreamingHostUpdate(remoteUserUid:number|string, { hasAudio, hasVideo }:{ hasAudio:boolean, hasVideo:boolean }): void,\n}\n\n\nexport enum ParticipantRolesEnum {\n clerk = 'clerk',\n auctioneer = 'auctioneer',\n bidder = 'bidder',\n viewer = 'viewer',\n onsite = 'onsite',\n}\n\nexport type WebcastAuctionConnectData_TypeDef = {\n auctionId: number,\n auctionName?: string,\n\n participantId: number,\n participantRole: ParticipantRolesEnum,\n\n bidderNumber: string,\n bidderLabel: string,\n bidderCanPlaceBid: boolean,\n\n wbsHostname: string,\n wbsConnectToken: string,\n\n streamingAgoraAppId: string,\n streamingAgoraChannelName: string,\n streamingAgoraToken: string,\n\n currencyCode:string,\n\n defaultClerkIncrements:Array,\n\n screenType?: WebcastScreenTypeCodesEnum,\n};\n\n\n\nexport const ServerPushedMessageTypeEnum = Object.freeze({\n AuctionDataSnapshot: 'AuctionDataSnapshot',\n AuctionDataSyncStatusChanged: 'AuctionDataSyncStatusChanged',\n\n ParticipantsUpdated: 'ParticipantsUpdated', // received by clerk only\n\n WebcastStatusChanged: 'WebcastStatusChanged',\n RoundCreated: 'RoundCreated',\n BiddingUpdated: 'BiddingUpdated',\n RoundStopped: 'RoundStopped',\n LotsPassClosed: 'LotsPassClosed',\n\n ChoiceLotsSelected: 'ChoiceLotsSelected',\n\n ChatMessagePosted: 'ChatMessagePosted',\n\n StreamingHostUpdated: 'StreamingHostUpdated',\n\n\n ReplyToInvalidRequest: 'ReplyToInvalidRequest',\n});\n\n\nexport const ClientMessageTypeEnum = Object.freeze({\n BidPlace: 'BidPlace',\n ChoiceLotsSelect: 'ChoiceLotsSelect',\n ChatMessagePost: 'ChatMessagePost',\n\n // Clerk ONLY below\n AuctionDataSyncApply: 'AuctionDataSyncApply',\n WebcastStatusChange: 'WebcastStatusChange',\n RoundCreate: 'RoundCreate',\n AskingBidUpdate: 'AskingBidUpdate',\n PreBidPlace: 'PreBidPlace',\n BidRevise: 'BidRevise',\n RoundStop: 'RoundStop',\n ChoiceLotsAssign: 'ChoiceLotsAssign',\n LotsPassClose: 'LotsPassClose',\n\n StreamingHostUpdate: 'StreamingHostUpdate',\n});\n\n\n\n\nconst silentClientMsgTypes = [ ClientMessageTypeEnum.StreamingHostUpdate ];\n\nconst chatClientMsgTypes = [ ClientMessageTypeEnum.ChatMessagePost ];\nconst clientMsgTypesMapArray = [];\n// add the 'chat' msgTypes pairs\nchatClientMsgTypes.forEach(msgType => { clientMsgTypesMapArray.push([msgType, ChannelEnum.chat])});\nObject.getOwnPropertyNames(ClientMessageTypeEnum)\n .map(objKeyName => ClientMessageTypeEnum[objKeyName])\n .filter(msgType => ((chatClientMsgTypes.indexOf(msgType) === -1) && (silentClientMsgTypes.indexOf(msgType) === -1))) // exclude 'chat' and \"silent\" msgTypes\n .forEach(msgType => { clientMsgTypesMapArray.push([msgType, ChannelEnum.bidding])});\n\nexport const WbsCommChannelForClientMessageTypeMap = new Map(clientMsgTypesMapArray);\n\n\n\nconst serverMsgTypesMapArray = [];\nconst silentServerMsgTypes = [ ClientMessageTypeEnum.StreamingHostUpdate ];\nconst chatServerMsgTypes = [ ServerPushedMessageTypeEnum.ChatMessagePosted ];\n// add the 'chat' msgTypes pairs\nchatServerMsgTypes.forEach(msgType => { serverMsgTypesMapArray.push([msgType, ChannelEnum.chat])});\n// add the 'bidding' msgTypes pairs\nObject.getOwnPropertyNames(ServerPushedMessageTypeEnum)\n .map(objKeyName => ServerPushedMessageTypeEnum[objKeyName])\n .filter(msgType => ((chatServerMsgTypes.indexOf(msgType) === -1) && (silentServerMsgTypes.indexOf(msgType)))) // exclude 'chat' and \"silent\" msgTypes\n .forEach(msgType => { serverMsgTypesMapArray.push([msgType, ChannelEnum.bidding])});\n\nexport const WbsCommChannelForServerPushedMessageTypeMap = new Map(serverMsgTypesMapArray);\n// exception: all channels are affected by these ServerMessages\nWbsCommChannelForServerPushedMessageTypeMap.set(ServerPushedMessageTypeEnum.AuctionDataSnapshot, ChannelEnum.all);\nWbsCommChannelForServerPushedMessageTypeMap.set(ServerPushedMessageTypeEnum.ReplyToInvalidRequest, ChannelEnum.all);\n\n\n\n\n\n\nlet _currentWebcastAuctionHandler:WebcastAuctionHandler;\nlet _reduxStore:Store;\n\n\nconst _logger = TaggedLogger.get('AuctionsManager');\n\n\nexport default class AuctionsManager {\n\n\n static init(reduxStore:Store):void {\n _reduxStore = reduxStore;\n }\n\n\n\n\n static leaveWebcast():Promise {\n if (_currentWebcastAuctionHandler) {\n _currentWebcastAuctionHandler._destroy();\n _currentWebcastAuctionHandler = null;\n }\n return Promise.resolve();\n }\n\n\n\n\n\n\n\n\n /**\n * @param auctionConnectData\n * @returns {WebcastAuctionHandler}\n */\n static createWebcastAuctionHandler(auctionConnectData:WebcastAuctionConnectData_TypeDef):WebcastAuctionHandler {\n\n // cleanup previous handler to avoid mem-leaks\n if (_currentWebcastAuctionHandler) {\n throw new Error('.createWebcastAuctionHandler FAILED: existing _currentWebcastAuctionHandler')\n // _logger.warn('.createWebcastAuctionHandler: destroying existing webcastAuctionHandler. This is a possible bug! You need to call `AuctionsManager.leaveWebcast()` to cleanup nicely');\n // _currentWebcastAuctionHandler._destroy();\n // _currentWebcastAuctionHandler = null;\n }\n\n\n // update redux state with this auction (will clear/destroy any data from previous auction handler, if existed)\n _reduxStore.dispatch(ActionsCreators.webcast.webcastAuctionInit(auctionConnectData));\n\n _currentWebcastAuctionHandler = new WebcastAuctionHandler(auctionConnectData);\n\n return _currentWebcastAuctionHandler;\n }\n\n\n static get currentWebcastAuctionHandler():WebcastAuctionHandler {\n return _currentWebcastAuctionHandler;\n }\n\n}\n\n\n// DEBUG\n// window._dev_AuctionsManager = AuctionsManager;\n\n\nexport type MediaStreamingHostsUpdateType = {\n wbsAudioUid?:number|string,\n wbsVideoUid?:number|string,\n}\n\nconst _loggerMSH = TaggedLogger.get('MediaStreamingHandler');\n\n\nclass MediaStreamingHandler {\n\n listenerFn:(MediaStreamingHostsUpdateType)=>void = null;\n pendingUpdate:MediaStreamingHostsUpdateType = null;\n\n\n onMediaStreamingHostsUpdated(listener:(update:MediaStreamingHostsUpdateType)=>void):()=>void {\n\n if (this.listenerFn) {\n throw 'MediaStreamingHandler.onMediaStreamingHostsUpdated: listener already registered';\n }\n\n // register listener\n this.listenerFn = listener;\n\n // fire any pending change if exists\n if (this.pendingUpdate) {\n this.listenerFn(this.pendingUpdate);\n }\n\n return () => {\n this.listenerFn = null;\n }\n }\n\n\n\n $update(update:MediaStreamingHostsUpdateType) {\n _loggerMSH.debug('.$update(): ', update);\n\n // if there is a listener registered\n if (this.listenerFn) {\n // trigger the registered listener\n this.listenerFn(update);\n }\n else {\n // save the last unsent change event\n this.pendingUpdate = update;\n }\n }\n\n\n $destroy() {\n _loggerMSH.debug('.$destroy()');\n\n this.listenerFn && this.listenerFn(null);\n // remove listener\n this.listenerFn = null;\n }\n}\n\n\n\n\nconst _loggerWSH = TaggedLogger.get('AuctionsManager::WebcastAuctionHandler');\n\n\n\n/**\n * @private\n */\nexport class WebcastAuctionHandler {\n\n public readonly auctionConnectData:WebcastAuctionConnectData_TypeDef;\n public readonly myUserId:number;\n wsConn:WebSocket;\n connectedWS = false;\n private _controller:WebcastAuctionHandlerControllerType;\n _heartbeatInterval = null;\n _fetchAuctionDataDetailsCachedResult:Array = null;\n _fetchAuctionDataDetailsPromise:Promise> = null;\n\n _heartbeatPongReceived:boolean = false;\n _heartbeatPingSentTimestamp:number = 0;\n\n private readonly _mediaStreamingHandler:MediaStreamingHandler;\n\n private _remoteDataHandler: AppRemoteDataHandler;\n\n\n constructor(auctionConnectData:WebcastAuctionConnectData_TypeDef) {\n this.auctionConnectData = auctionConnectData;\n this.myUserId = auctionConnectData.participantId;\n this._mediaStreamingHandler = new MediaStreamingHandler();\n }\n\n\n\n /**\n * This is the MAIN \"igniter\" for all events triggered during a Webcast auction.\n *\n * It starts 2 connections:\n * - websockets to WBS\n * - http fetch to FrontendAPI (Rails)\n *\n * @returns {Promise} when connection is open, resolves `true`; if error, rejects\n */\n public async connect():Promise {\n\n const wsUrlEndpoint = new URI(`wss://${this.auctionConnectData.wbsHostname}/ws/${this.auctionConnectData.participantRole}`)\n .query({\n aid: this.auctionConnectData.auctionId,\n uid: this.auctionConnectData.participantId,\n token: this.auctionConnectData.wbsConnectToken\n })\n .toString();\n\n\n _loggerWSH.info('.connect: ', wsUrlEndpoint);\n\n\n // initialize the controller we'll use to send commands (send WBS messages, misc actions, etc)\n this._controller = {\n\n sendWebcastStatusChange: (statusData):void => {\n this._sendWbsMessage(ClientMessageTypeEnum.WebcastStatusChange, statusData);\n },\n\n sendAuctionDataSyncApply: ():void => {\n this._sendWbsMessage(ClientMessageTypeEnum.AuctionDataSyncApply);\n },\n\n\n sendRoundCreate: (roundType, lotsIds):void => {\n this._sendWbsMessage(ClientMessageTypeEnum.RoundCreate, { lotsIds, roundType });\n },\n\n sendRoundStop: (roundId:string, stopType:number):void => {\n this._sendWbsMessage(ClientMessageTypeEnum.RoundStop, { roundId, stopType });\n },\n\n sendAskingBidUpdate: (roundId:string, askingBidValue:number):void => {\n this._sendWbsMessage(ClientMessageTypeEnum.AskingBidUpdate, { roundId, askingBidValue })\n },\n\n sendBidRevise: (roundId:string, reviseType:number, bidValue:number):void => {\n this._sendWbsMessage(ClientMessageTypeEnum.BidRevise, { roundId, reviseType, bidValue })\n },\n\n\n sendBidPlace: (roundId:string, value:number):void => {\n this._sendWbsMessage(ClientMessageTypeEnum.BidPlace, { roundId, value });\n },\n\n sendPreBidPlace: (roundId: string, bidderUserId: number, value: number):void => {\n this._sendWbsMessage(ClientMessageTypeEnum.PreBidPlace, { roundId, bidderUserId, value });\n },\n\n sendChoiceLotsSelection: (roundId: string, lotsIds:Array):void => {\n this._sendWbsMessage(ClientMessageTypeEnum.ChoiceLotsSelect, { roundId, lotsIds });\n },\n\n sendChoiceLotsAssignment: (roundId: string, lotsIds:Array, usersIds:Array, nextRoundType:number):void => {\n this._sendWbsMessage(ClientMessageTypeEnum.ChoiceLotsAssign, { roundId, lotsIds, usersIds, nextRoundType });\n },\n\n\n sendLotsPass: (lotsIds: Array):void => {\n this._sendWbsMessage(ClientMessageTypeEnum.LotsPassClose, { lotsIds });\n },\n\n sendChatMessage: (roomId:number, body:string):void => {\n _reduxStore.dispatch(ActionsCreators.webcast.webcastChatRoomOpenAndMarkAsRead(roomId));\n this._sendWbsMessage(ClientMessageTypeEnum.ChatMessagePost, { roomId, body });\n },\n\n sendStreamingHostUpdate: (streamId:number, { hasAudio, hasVideo }):void => {\n const msgData:{audioUid?:number, videoUid?:number} = {};\n if (hasAudio) {\n msgData.audioUid = streamId;\n }\n if (hasVideo) {\n msgData.videoUid = streamId;\n }\n\n this._sendWbsMessage(ClientMessageTypeEnum.StreamingHostUpdate, msgData);\n },\n\n openChatRoomAndMarkAsRead: (roomId:number):void => {\n _reduxStore.dispatch(ActionsCreators.webcast.webcastChatRoomOpenAndMarkAsRead(roomId));\n },\n\n closeChatRoom: (roomId:number):void => {\n _reduxStore.dispatch(ActionsCreators.webcast.webcastChatRoomClose(roomId));\n }\n };\n\n\n this._remoteDataHandler = new AppRemoteDataHandler({ siteId: DataStore.config.site_id, frontendApiBaseUrl: DataStore.config.frontend_api_base_url });\n\n\n return new Promise((resolve, reject) => {\n let promiseResolved = 0;\n\n try {\n this.wsConn = new WebSocket(wsUrlEndpoint);\n }\n catch (ex) {\n promiseResolved = -11; // error code `1x` are for the WS conn\n reject(ex.toString());\n return; // stop here\n }\n\n this.wsConn.binaryType = \"arraybuffer\";\n\n this.wsConn.addEventListener('open', (evt: Event) => {\n if (promiseResolved !== 0) {\n _loggerWSH.warn('wsConn>open: connected, BUT previous error encountered! promiseResolved:', promiseResolved);\n this.wsConn.close(4002);\n return;\n }\n\n _loggerWSH.debug('wsConn>open: readyState:', this.wsConn.readyState, evt);\n\n this.connectedWS = true;\n promiseResolved = 11;\n\n this._heartbeatPongReceived = true;\n this._heartbeatPingSentTimestamp = Date.now(); // initialize\n\n this._heartbeatInterval = setInterval(() => {\n if (this._heartbeatPongReceived) {\n this._heartbeatPongReceived = false;\n this._heartbeatPingSentTimestamp = Date.now();\n this.wsConn && this.wsConn.send('[1]'); // send ping\n }\n else {\n _loggerWSH.warn('wsConn>open: heartbeat: pong-reply timeout! closing with code 4006');\n this._destroy(4006);\n }\n }, 25 * 1000); // 25 seconds : https://tools.ietf.org/html/rfc6455#section-5.5.2\n\n _reduxStore.dispatch(ActionsCreators.webcast.wbsNetworkStatusUpdate({ connectionState: WbsNetworkStatusConnectionStateEnum.connected, roundTripMilliseconds: 1 }));\n\n resolve(true);\n })\n\n\n this.wsConn.addEventListener('close', (evt: CloseEvent) => {\n _loggerWSH.debug('wsConn>close: ', evt);\n this.wsConn = null; // if closed, then never recover, remove reference to avoid mem-leak\n this.connectedWS = false;\n if (this._heartbeatInterval) {\n clearInterval(this._heartbeatInterval);\n this._heartbeatInterval = null;\n }\n\n _reduxStore.dispatch(ActionsCreators.webcast.wbsNetworkStatusUpdate({ connectionState: WbsNetworkStatusConnectionStateEnum.disconnected, roundTripMilliseconds: 0 }));\n\n this._handleWSClose();\n })\n\n\n this.wsConn.addEventListener('message', async (evt) => {\n // const dataStr = ab2str(evt.data);\n // const data = JSON.parse(dataStr);\n const msgStr = evt.data;\n\n // handle 'pong'\n if (msgStr && msgStr === '[2]') {\n this._heartbeatPongReceived = true;\n _reduxStore.dispatch(ActionsCreators.webcast.wbsNetworkStatusUpdate({ connectionState: WbsNetworkStatusConnectionStateEnum.connected, roundTripMilliseconds: Date.now() - this._heartbeatPingSentTimestamp }));\n return;\n }\n\n const msg: WBSWebsocketMessage = JSON.parse(msgStr);\n _loggerWSH.debug('wsConn>message: ', msg);\n const msgType = msg[0];\n const msgPayload = msg[1];\n await this._handleOnWbsMessageReceived(msgType, msgPayload);\n })\n\n\n this.wsConn.addEventListener('error', (evt) => {\n _loggerWSH.debug('wsConn>error: ', 'readyState:', this.wsConn.readyState, 'event: ', evt);\n this._destroy(4001);\n if (promiseResolved === 0) {\n promiseResolved = -12;\n reject(evt);\n }\n })\n\n\n\n // fetch Auction & Lots details via Frontend-API\n this._fetchAuctionDataDetails(true).catch((rejectCause) => {\n if (promiseResolved === 0) {\n promiseResolved = -21; // error code `2x` are for the API fetch\n reject(\".connect.reject: _fetchAuctionDataDetails.catch: \" + rejectCause + \"\\n\" + rejectCause.stack);\n }\n })\n\n });\n }\n\n\n /**\n * Private method, should NOT be called directly. Use `AuctionsManager.leaveWebcast()`\n * @param wsCloseCode\n * @private\n */\n _destroy(wsCloseCode:number = 4009) {\n if (this.wsConn) {\n this.wsConn.close(wsCloseCode); // app-specific error connection close\n this.wsConn = null;\n this.connectedWS = false;\n }\n }\n\n private _handleWSClose() {\n this._mediaStreamingHandler.$destroy();\n _reduxStore.dispatch(ActionsCreators.webcast.webcastAuctionClear());\n }\n\n\n\n get controller():WebcastAuctionHandlerControllerType {\n return this._controller;\n }\n\n\n get mediaStreamingHandler():MediaStreamingHandler {\n return this._mediaStreamingHandler;\n }\n\n\n\n formatCurrencyAmount(valueCents:number, displayForEmpty:string = ''):string {\n if (!valueCents && valueCents !== 0) {\n return displayForEmpty;\n }\n const moneyHelper = getMoneyHelperForCurrencyCode(this.auctionConnectData.currencyCode)\n return moneyHelper.formatFromCents(valueCents);\n }\n\n\n\n\n private _fetchAuctionDataDetails(forceRefresh:boolean = false):Promise> {\n _loggerWSH.debug('._fetchAuctionDataDetails() forceRefresh:', forceRefresh);\n\n if (this._fetchAuctionDataDetailsPromise && ! forceRefresh) {\n _loggerWSH.debug('._fetchAuctionDataDetails: return existing Promise');\n return this._fetchAuctionDataDetailsPromise;\n }\n\n\n this._fetchAuctionDataDetailsPromise = new Promise((resolve, reject) => {\n\n // if we have a cached (previously fetched) data, and it's not a forced refresh, then resolve with the cached data\n if (this._fetchAuctionDataDetailsCachedResult && ! forceRefresh) {\n _loggerWSH.debug('._fetchAuctionDataDetails:Promise> resolve from cache');\n resolve(this._fetchAuctionDataDetailsCachedResult);\n return;\n }\n\n // fetch Auction & Lot details (description, images)\n this._remoteDataHandler.fetchAuctionWebcastLots(this.auctionConnectData.auctionId)\n .then((lots) => {\n this._fetchAuctionDataDetailsCachedResult = lots;\n resolve(this._fetchAuctionDataDetailsCachedResult);\n },\n\n (rejectReason) => {\n _loggerWSH.error('._fetchAuctionDataDetails:Promise>ApiService.getAuctionWebcastLots.reject: ', rejectReason, rejectReason.stack);\n reject(\"_fetchAuctionDataDetails.reject: \" + rejectReason + \"\\nstack: \" + rejectReason.stack);\n });\n });\n\n _loggerWSH.debug('._fetchAuctionDataDetails: return new Promise');\n return this._fetchAuctionDataDetailsPromise;\n }\n\n\n\n private _sendWbsMessage(msgType:string, msgData?:{}) {\n _loggerWSH.debug('wsConn.send: ', msgType, msgData);\n\n if (this.wsConn && this.wsConn.readyState === 1) { // OPEN\n\n const channel = WbsCommChannelForClientMessageTypeMap.get(msgType);\n if (channel) {\n //only dispatch non-silent messages\n _reduxStore.dispatch(ActionsCreators.webcast.wbsCommStateUpdate({ channel, newStatus: WbsCommStatesEnum.WBS_COMM_STATUS_SENDING }));\n }\n\n const data = [ msgType, msgData ];\n const dataStr = JSON.stringify(data);\n this.wsConn.send(dataStr);\n }\n else {\n throw 'WebcastAuctionHandler.sendMessage() FAILED: WebSocket connection is not OPEN!'\n }\n }\n\n\n\n private async _handleOnWbsMessageReceived(msgType:string, msgPayloadObj:any) {\n\n const currentReduxState:ReduxStateType = _reduxStore.getState();\n const currentActiveWebcastReduxState:ReduxActiveWebcastSubStateType = currentReduxState.activeWebcast;\n\n const channel = WbsCommChannelForServerPushedMessageTypeMap.get(msgType);\n _reduxStore.dispatch(ActionsCreators.webcast.wbsCommStateUpdate({ channel, newStatus: WbsCommStatesEnum.WBS_COMM_STATUS_IDLE }));\n\n\n switch(msgType) {\n\n case ServerPushedMessageTypeEnum.AuctionDataSnapshot: {\n const msgPayload:PMAuctionDataSnapshot = msgPayloadObj;\n _reduxStore.dispatch(ActionsCreators.webcast.webcastAuctionDataSnapshotInit(msgPayload));\n\n const lotsDetails = await this._fetchAuctionDataDetails(false);\n _reduxStore.dispatch(ActionsCreators.webcast.webcastAuctionDataLotsDetailsUpdate({ lotsDetails }));\n\n this._mediaStreamingHandler.$update({ wbsAudioUid: msgPayload.streamingAudioUid, wbsVideoUid: msgPayload.streamingVideoUid });\n\n break;\n }\n\n\n case ServerPushedMessageTypeEnum.AuctionDataSyncStatusChanged: {\n const msgPayload:PMAuctionDataSyncStatusChanged = msgPayloadObj;\n\n if (msgPayload.outOfSync && msgPayload.mustApply) {\n if (msgPayload.lots?.length) {\n // only dispatch when mustApply and there's a lots \"list\" update\n _reduxStore.dispatch(ActionsCreators.webcast.webcastAuctionDataSyncLotsListUpdate(msgPayload.lots));\n }\n\n // always update lot details if out of sync and mustApply\n const lotsDetails = await this._fetchAuctionDataDetails(true);\n _reduxStore.dispatch(ActionsCreators.webcast.webcastAuctionDataLotsDetailsUpdate({ lotsDetails, isDataSync: true }));\n\n _reduxStore.dispatch(ActionsCreators.webcast.webcastClerkAuctionDataSyncCheckStatusUpdate(true));\n }\n else {\n _reduxStore.dispatch(ActionsCreators.webcast.webcastClerkAuctionDataSyncCheckStatusUpdate(msgPayload.outOfSync));\n }\n\n break;\n }\n\n\n\n case ServerPushedMessageTypeEnum.ParticipantsUpdated: {\n _reduxStore.dispatch(ActionsCreators.webcast.webcastClerkParticipantsUpdate(msgPayloadObj));\n break;\n }\n\n\n case ServerPushedMessageTypeEnum.WebcastStatusChanged: {\n _reduxStore.dispatch(ActionsCreators.webcast.webcastStatusChange(msgPayloadObj));\n break;\n }\n\n\n case ServerPushedMessageTypeEnum.RoundCreated: {\n _reduxStore.dispatch(ActionBuilder.build(ACTION_TYPES.WEBCAST_CURRENT_ROUND_CREATE, msgPayloadObj));\n break;\n }\n\n\n case ServerPushedMessageTypeEnum.BiddingUpdated: {\n _reduxStore.dispatch(ActionBuilder.build(ACTION_TYPES.WEBCAST_CURRENT_ROUND_BIDDING_UPDATE, msgPayloadObj));\n break;\n }\n\n\n case ServerPushedMessageTypeEnum.RoundStopped: {\n const msgPayload:PMRoundStopped = msgPayloadObj;\n\n const roundStopWaitTime = msgPayload.stopType === RoundStopTypeEnum.CANCEL ? 1500 : 2000;\n\n const roundType = currentActiveWebcastReduxState.webcastCurrentRound.roundType;\n\n const roundStopActionPayload:CurrentRoundStopActionPayloadType = {\n ... msgPayload,\n roundType: roundType,\n highestBid: currentActiveWebcastReduxState.webcastCurrentRoundBidding.highestBid,\n isTransitional: true, // first-time dispatch of ROUND_STOP is *always* transitional\n };\n\n\n // dispatch the ROUND_STOP action (with isTransitional:true), regardless of roundType or stopType\n _reduxStore.dispatch(ActionsCreators.webcast.webcastCurrentRoundStop(roundStopActionPayload));\n\n\n if (msgPayload.nextRound) {\n // `nextRound` is present when the currentRound will be closed (finished)\n // `nextRound` is sent null from server when stopping a CHOICE round as SOLD|PENDING, but it *is* present when the CHOICE round is *closed*\n const roundCloseActionPayload:CurrentRoundCloseActionPayloadType = {\n roundId: msgPayload.roundId,\n roundType: roundType,\n stopType: msgPayload.stopType,\n lotsIds: currentActiveWebcastReduxState.webcastCurrentRound.lotsIds,\n bidsHistory: currentActiveWebcastReduxState.webcastCurrentRoundBidding.bidsHistory,\n highestBid: currentActiveWebcastReduxState.webcastCurrentRoundBidding.highestBid,\n\n nextRound: msgPayload.nextRound, // include nextRound\n };\n\n // this may be a CHOICE round closing\n if (msgPayload.choiceLotsIds && msgPayload.choiceLotsIds.length) {\n // if there are selections, send them in the action payload\n roundCloseActionPayload.choiceLotsIds = msgPayload.choiceLotsIds;\n roundCloseActionPayload.choiceUsersIds = msgPayload.choiceUsersIds;\n }\n\n\n setTimeout(() => {\n _reduxStore.dispatch(ActionsCreators.webcast.webcastCurrentRoundClose(roundCloseActionPayload));\n }, roundStopWaitTime);\n }\n else {\n // a CHOICE stopping as SOLD|PENDING (`nextRound` is sent null from server)\n // re-dispatch the ROUND_STOP action but with `isTransitional:false`\n setTimeout(() => {\n _reduxStore.dispatch(ActionsCreators.webcast.webcastCurrentRoundStop({ ... roundStopActionPayload, isTransitional: false } ));\n }, roundStopWaitTime);\n\n }\n break;\n }\n\n\n\n case ServerPushedMessageTypeEnum.ChoiceLotsSelected: {\n _reduxStore.dispatch(ActionsCreators.webcast.choiceLotsSelectionUpdate(msgPayloadObj));\n break;\n }\n\n\n\n\n\n case ServerPushedMessageTypeEnum.LotsPassClosed: {\n _reduxStore.dispatch(ActionBuilder.build(ACTION_TYPES.WEBCAST_LOTS_PASS_CLOSE, msgPayloadObj));\n break;\n }\n\n\n\n case ServerPushedMessageTypeEnum.ChatMessagePosted: {\n _reduxStore.dispatch(ActionsCreators.webcast.webcastChatMessagePost(msgPayloadObj));\n break;\n }\n\n\n\n case ServerPushedMessageTypeEnum.StreamingHostUpdated: {\n this._mediaStreamingHandler.$update({ wbsAudioUid: msgPayloadObj.audioUid, wbsVideoUid: msgPayloadObj.videoUid });\n break;\n }\n\n }\n }\n\n}\n", "// https://immerjs.github.io/immer/installation/\nimport {enableMapSet} from \"immer\";\nenableMapSet();\n\n\nimport AuctionsManager, {WebcastAuctionConnectData_TypeDef, WebcastAuctionHandler} from \"./services/AuctionsManager\";\nimport DataStore, {ReduxStateType} from \"./services/DataStore\";\nimport {ReduxActiveWebcastSubStateType} from \"./redux/reducerActiveWebcast\";\nimport { WebcastStateEnum, RoundTypeEnum, LotStateEnum, RoundStopTypeEnum } from \"./data/WebcastDataDomain\";\n\n\nexport {\n AuctionsManager,\n DataStore,\n WebcastStateEnum,\n WebcastAuctionHandler,\n RoundTypeEnum,\n LotStateEnum,\n RoundStopTypeEnum\n};\n\n\nexport type {\n WebcastAuctionConnectData_TypeDef,\n ReduxStateType as WebcastReduxState_TypeDef,\n ReduxActiveWebcastSubStateType as WebcastReduxActiveWebcastSubState_TypeDef\n};\n\n\n", "import React from \"react\";\nimport {connect} from \"react-redux\";\nimport {DateTime} from \"luxon\";\nimport NetworkAwareBusyOverlayCmp from \"../NetworkAwareBusyOverlayCmp\";\nimport {ReduxActiveWebcastSubStateType} from \"@nextlot/core/webcast/redux/reducerActiveWebcast\";\nimport {ChatRoom, Participant} from \"@nextlot/core/webcast/data/data_types_definitions\";\nimport {TaggedLogger} from \"@nextlot/core/utilities\";\nimport {AuctionsManager} from \"@nextlot/core/webcast\";\nimport {ReduxWebcastChatType} from \"@nextlot/core/webcast/redux/webcast/reducerWebcastChat\";\nimport {ChannelEnum} from \"@nextlot/core/webcast/redux/actions\";\n\n\ntype RootCmpPropsType = {\n chat: ReduxWebcastChatType,\n participantsByUserId: Map,\n\n openChatRoom: (roomId:number)=>null|(()=>void),\n closeChatRoom: (roomId:number)=>void,\n};\n\ntype RootCmpStateType = {\n chatMessageText: string,\n}\n\n\nconst _logger = TaggedLogger.get('ClerkChatTabContentCmp');\n\n\nclass ClerkChatTabContentCmp extends React.Component {\n private readonly refMessagesListBottom: any;\n private readonly refInputChatTextbox: any;\n\n\n constructor(props) {\n super(props);\n _logger.debug('.constructor: ', props);\n\n this.refMessagesListBottom = React.createRef();\n this.refInputChatTextbox = React.createRef();\n\n\n this.state = {\n chatMessageText: '',\n }\n }\n\n\n componentDidMount(): void {\n this.scrollMessagesListToBottom();\n }\n\n\n\n componentDidUpdate(prevProps:RootCmpPropsType): void {\n const currentActiveChatRoomId:number = this.props.chat.activeChatRoomId;\n const currentActiveChatRoom:ChatRoom = this.props.chat.chatRoomsById.get(currentActiveChatRoomId);\n\n const prevActiveChatRoomId:number = prevProps.chat.activeChatRoomId;\n const prevActiveChatRoom:ChatRoom = prevProps.chat.chatRoomsById.get(prevActiveChatRoomId);\n\n if (currentActiveChatRoom) {\n if (currentActiveChatRoomId !== prevActiveChatRoomId) {\n // active selected ChatRoom changed => focus input\n this.refInputChatTextbox && this.refInputChatTextbox.current && this.refInputChatTextbox.current.focus();\n this.scrollMessagesListToBottom();\n }\n else {\n // same ChatRoom.id, but different objects? (means chat messages changed)\n if (prevActiveChatRoom !== currentActiveChatRoom) {\n this.scrollMessagesListToBottom();\n }\n }\n }\n }\n\n\n\n\n\n getChatRoomLabel(chatRoom:ChatRoom) {\n let chatRoomLabel;\n if (chatRoom.id === -1) {\n chatRoomLabel = 'ALL (BROADCAST)';\n }\n else if (chatRoom.id === 0) {\n chatRoomLabel = 'ADMIN';\n }\n else {\n const roomOwner:Participant = this.props.participantsByUserId.get(chatRoom.id);\n if (!roomOwner) {\n return '[offline] Participant#' + chatRoom.id;\n }\n chatRoomLabel = `${roomOwner.bidderNo} (${roomOwner.bidderLabel})`;\n }\n return chatRoomLabel;\n }\n\n\n\n scrollMessagesListToBottom = () => {\n this.refMessagesListBottom && this.refMessagesListBottom.current && this.refMessagesListBottom.current.scrollIntoView({ behavior: 'auto' });\n };\n\n\n\n handleClick_ChatRoomListItem = (chatRoom:ChatRoom) => (event) => {\n this.setState({\n chatMessageText: ''\n });\n\n this.props.openChatRoom(chatRoom.id);\n };\n\n\n handleClick_ChatRoomClose = (chatRoom:ChatRoom) => (event) => {\n this.setState({\n chatMessageText: ''\n });\n\n this.props.closeChatRoom(chatRoom.id);\n };\n\n\n handleChange_ChatMessageInput = (event) => {\n this.setState({ chatMessageText: event.target.value });\n };\n\n\n handleFormSubmit_ChatMessageForm = (event) => {\n event.preventDefault();\n AuctionsManager.currentWebcastAuctionHandler.controller.sendChatMessage(this.props.chat.activeChatRoomId, this.state.chatMessageText);\n this.setState({ chatMessageText: '' });\n };\n\n\n\n\n\n renderChatRoomsListItem(chatRoom:ChatRoom) {\n if (! this.props.participantsByUserId.get(chatRoom.id)) {\n\n }\n\n const chatRoomLabel = this.getChatRoomLabel(chatRoom);\n return (\n
\n
\n {chatRoomLabel}\n {\n (chatRoom.unreadCount && chatRoom.unreadCount > 0) ?\n ({chatRoom.unreadCount})\n :\n null\n }\n
\n\n {(chatRoom.id !== 0 && chatRoom.id !== -1) &&\n
×
\n }\n
\n )\n }\n\n\n\n\n renderActiveChatRoom() {\n const chatRoom:ChatRoom = this.props.chat.chatRoomsById.get(this.props.chat.activeChatRoomId);\n\n if (! chatRoom) {\n return null;\n }\n\n const chatRoomLabel = this.getChatRoomLabel(chatRoom);\n return (\n
\n
Chat: {chatRoomLabel}
\n\n
\n
\n {chatRoom.messages.map(chatMsg => this.renderChatMessageListItem(chatMsg))}\n
 
\n
\n
\n\n
\n
 ≡ 
\n \n \n \n
\n )\n }\n\n\n renderChatMessageListItem(chatMsg) {\n const direction = chatMsg.sender === this.props.chat.myUserInfo.senderUserId ? 'ours' : 'theirs';\n const dtStr = DateTime.fromMillis(chatMsg.timestamp).toLocal().toFormat('h:mma');\n return (\n
\n
{chatMsg.body}
\n
{dtStr}
\n
\n )\n }\n\n\n\n\n render() {\n // _logger.debug('.render() props:', this.props);\n\n return (\n
\n \n\n
\n
\n {this.props.chat.chatRooms\n .filter((chatRoom:ChatRoom) => !chatRoom.isClosed)\n .map((chatRoom:ChatRoom) => this.renderChatRoomsListItem(chatRoom))}\n
\n
\n\n {this.renderActiveChatRoom()}\n
\n )\n }\n}\n\n\n\nexport default connect(({ activeWebcast }: {activeWebcast:ReduxActiveWebcastSubStateType}) => {\n return {\n webcastStatus: activeWebcast.webcastStatus,\n participantsByUserId: activeWebcast.webcastParticipants.mapByUserId,\n chat: activeWebcast.webcastChat,\n };\n})(ClerkChatTabContentCmp);\n\n\n", "import React from \"react\";\nimport {connect} from \"react-redux\";\nimport ClerkBiddersListTabContentCmp from \"./ClerkBiddersListTabContentCmp\";\nimport ClerkChatTabContentCmp from \"./ClerkChatTabContentCmp\";\nimport {TaggedLogger} from \"@nextlot/core/utilities\";\nimport {AuctionsManager} from \"@nextlot/core/webcast\";\nimport {ReduxStateType} from \"@nextlot/core/webcast/services/DataStore\";\n\nconst TAB_CHAT = 'tab_chat';\nconst TAB_BIDDERS = 'tab_bidders';\n\n\n\ntype RootCmpPropsType = {\n participants: {\n onlineBidders: [],\n offlineBidders: [],\n onlineViewers: [],\n offlineViewers: [],\n }\n};\n\n\ntype CmpStateType = {\n activeTab:string,\n};\n\n\nconst _logger = TaggedLogger.get('ClerkBiddersListAndChatRootCmp');\n\n\nclass ClerkBiddersListAndChatRootCmp extends React.Component {\n\n\n constructor(props) {\n super(props);\n\n this.state = {\n activeTab: TAB_CHAT,\n }\n }\n\n\n\n\n isActiveTabEqualTo = (tabId) => {\n return (this.state.activeTab === tabId)\n };\n\n\n\n handleTabClick = (tabId) => (evt) => {\n evt.preventDefault();\n\n if (this.isActiveTabEqualTo(tabId)) {\n return\n }\n\n this.setState({\n activeTab: tabId\n });\n };\n\n\n handleOpenChatRoom = (roomId:number) => {\n this.setState({\n activeTab: TAB_CHAT,\n }, () => {\n AuctionsManager.currentWebcastAuctionHandler.controller.openChatRoomAndMarkAsRead(roomId);\n });\n };\n\n handleCloseChatRoom = (roomId:number) => {\n AuctionsManager.currentWebcastAuctionHandler.controller.closeChatRoom(roomId);\n };\n\n\n\n render() {\n return (\n
\n );\n }\n}\n\n\nexport default connect(({ activeWebcast }:ReduxStateType) => {\n return {\n participants: activeWebcast.webcastParticipants\n };\n})(ClerkBiddersListAndChatRootCmp);\n\n\n", "/*!\n\tCopyright (c) 2018 Jed Watson.\n\tLicensed under the MIT License (MIT), see\n\thttp://jedwatson.github.io/classnames\n*/\n/* global define */\n\n(function () {\n\t'use strict';\n\n\tvar hasOwn = {}.hasOwnProperty;\n\n\tfunction classNames () {\n\t\tvar classes = '';\n\n\t\tfor (var i = 0; i < arguments.length; i++) {\n\t\t\tvar arg = arguments[i];\n\t\t\tif (arg) {\n\t\t\t\tclasses = appendClass(classes, parseValue(arg));\n\t\t\t}\n\t\t}\n\n\t\treturn classes;\n\t}\n\n\tfunction parseValue (arg) {\n\t\tif (typeof arg === 'string' || typeof arg === 'number') {\n\t\t\treturn arg;\n\t\t}\n\n\t\tif (typeof arg !== 'object') {\n\t\t\treturn '';\n\t\t}\n\n\t\tif (Array.isArray(arg)) {\n\t\t\treturn classNames.apply(null, arg);\n\t\t}\n\n\t\tif (arg.toString !== Object.prototype.toString && !arg.toString.toString().includes('[native code]')) {\n\t\t\treturn arg.toString();\n\t\t}\n\n\t\tvar classes = '';\n\n\t\tfor (var key in arg) {\n\t\t\tif (hasOwn.call(arg, key) && arg[key]) {\n\t\t\t\tclasses = appendClass(classes, key);\n\t\t\t}\n\t\t}\n\n\t\treturn classes;\n\t}\n\n\tfunction appendClass (value, newClass) {\n\t\tif (!newClass) {\n\t\t\treturn value;\n\t\t}\n\t\n\t\tif (value) {\n\t\t\treturn value + ' ' + newClass;\n\t\t}\n\t\n\t\treturn value + newClass;\n\t}\n\n\tif (typeof module !== 'undefined' && module.exports) {\n\t\tclassNames.default = classNames;\n\t\tmodule.exports = classNames;\n\t} else if (typeof define === 'function' && typeof define.amd === 'object' && define.amd) {\n\t\t// register as 'classnames', consistent with npm package name\n\t\tdefine('classnames', [], function () {\n\t\t\treturn classNames;\n\t\t});\n\t} else {\n\t\twindow.classNames = classNames;\n\t}\n}());\n", "/**\n * AgoraWebSDK_N-v4.20.2-0-g8ae7fdad Copyright AgoraInc.\n */\n\n!function(e,t){\"object\"==typeof exports&&\"undefined\"!=typeof module?module.exports=t():\"function\"==typeof define&&define.amd?define(t):(e=\"undefined\"!=typeof globalThis?globalThis:e||self).AgoraRTC=t()}(this,(function(){\"use strict\";function e(e,t){return t.forEach((function(t){t&&\"string\"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach((function(i){if(\"default\"!==i&&!(i in e)){var n=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,n.get?n:{enumerable:!0,get:function(){return t[i]}})}}))})),Object.freeze(e)}var t=\"undefined\"!=typeof globalThis?globalThis:\"undefined\"!=typeof window?window:\"undefined\"!=typeof global?global:\"undefined\"!=typeof self?self:{};function i(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,\"default\")?e.default:e}var n=function(e){try{return!!e()}catch(e){return!0}},r=!n((function(){var e=function(){}.bind();return\"function\"!=typeof e||e.hasOwnProperty(\"prototype\")})),s=r,o=Function.prototype,a=o.call,c=s&&o.bind.bind(a,a),d=s?c:function(e){return function(){return a.apply(e,arguments)}},l=d({}.isPrototypeOf),u=function(e){return e&&e.Math==Math&&e},h=u(\"object\"==typeof globalThis&&globalThis)||u(\"object\"==typeof window&&window)||u(\"object\"==typeof self&&self)||u(\"object\"==typeof t&&t)||function(){return this}()||t||Function(\"return this\")(),p=r,_=Function.prototype,E=_.apply,m=_.call,f=\"object\"==typeof Reflect&&Reflect.apply||(p?m.bind(E):function(){return m.apply(E,arguments)}),g=d,T=g({}.toString),S=g(\"\".slice),R=function(e){return S(T(e),8,-1)},C=R,I=d,v=function(e){if(\"Function\"===C(e))return I(e)},y=\"object\"==typeof document&&document.all,A={all:y,IS_HTMLDDA:void 0===y&&void 0!==y},b=A.all,w=A.IS_HTMLDDA?function(e){return\"function\"==typeof e||e===b}:function(e){return\"function\"==typeof e},O={},N=!n((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]})),D=r,P=Function.prototype.call,L=D?P.bind(P):function(){return P.apply(P,arguments)},k={},M={}.propertyIsEnumerable,U=Object.getOwnPropertyDescriptor,x=U&&!M.call({1:2},1);k.f=x?function(e){var t=U(this,e);return!!t&&t.enumerable}:M;var V,F,B=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},j=n,G=R,W=Object,H=d(\"\".split),K=j((function(){return!W(\"z\").propertyIsEnumerable(0)}))?function(e){return\"String\"==G(e)?H(e,\"\"):W(e)}:W,Y=function(e){return null==e},q=Y,z=TypeError,J=function(e){if(q(e))throw z(\"Can't call method on \"+e);return e},X=K,Q=J,Z=function(e){return X(Q(e))},$=w,ee=A.all,te=A.IS_HTMLDDA?function(e){return\"object\"==typeof e?null!==e:$(e)||e===ee}:function(e){return\"object\"==typeof e?null!==e:$(e)},ie={},ne=ie,re=h,se=w,oe=function(e){return se(e)?e:void 0},ae=function(e,t){return arguments.length<2?oe(ne[e])||oe(re[e]):ne[e]&&ne[e][t]||re[e]&&re[e][t]},ce=\"undefined\"!=typeof navigator&&String(navigator.userAgent)||\"\",de=h,le=ce,ue=de.process,he=de.Deno,pe=ue&&ue.versions||he&&he.version,_e=pe&&pe.v8;_e&&(F=(V=_e.split(\".\"))[0]>0&&V[0]<4?1:+(V[0]+V[1])),!F&&le&&(!(V=le.match(/Edge\\/(\\d+)/))||V[1]>=74)&&(V=le.match(/Chrome\\/(\\d+)/))&&(F=+V[1]);var Ee=F,me=Ee,fe=n,ge=h.String,Te=!!Object.getOwnPropertySymbols&&!fe((function(){var e=Symbol();return!ge(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&me&&me<41})),Se=Te&&!Symbol.sham&&\"symbol\"==typeof Symbol.iterator,Re=ae,Ce=w,Ie=l,ve=Object,ye=Se?function(e){return\"symbol\"==typeof e}:function(e){var t=Re(\"Symbol\");return Ce(t)&&Ie(t.prototype,ve(e))},Ae=String,be=function(e){try{return Ae(e)}catch(e){return\"Object\"}},we=w,Oe=be,Ne=TypeError,De=function(e){if(we(e))return e;throw Ne(Oe(e)+\" is not a function\")},Pe=De,Le=Y,ke=function(e,t){var i=e[t];return Le(i)?void 0:Pe(i)},Me=L,Ue=w,xe=te,Ve=TypeError,Fe={exports:{}},Be=h,je=Object.defineProperty,Ge=function(e,t){try{je(Be,e,{value:t,configurable:!0,writable:!0})}catch(i){Be[e]=t}return t},We=\"__core-js_shared__\",He=h[We]||Ge(We,{}),Ke=He;(Fe.exports=function(e,t){return Ke[e]||(Ke[e]=void 0!==t?t:{})})(\"versions\",[]).push({version:\"3.31.1\",mode:\"pure\",copyright:\"\u00A9 2014-2023 Denis Pushkarev (zloirock.ru)\",license:\"https://github.com/zloirock/core-js/blob/v3.31.1/LICENSE\",source:\"https://github.com/zloirock/core-js\"});var Ye=Fe.exports,qe=J,ze=Object,Je=function(e){return ze(qe(e))},Xe=Je,Qe=d({}.hasOwnProperty),Ze=Object.hasOwn||function(e,t){return Qe(Xe(e),t)},$e=d,et=0,tt=Math.random(),it=$e(1..toString),nt=function(e){return\"Symbol(\"+(void 0===e?\"\":e)+\")_\"+it(++et+tt,36)},rt=Ye,st=Ze,ot=nt,at=Te,ct=Se,dt=h.Symbol,lt=rt(\"wks\"),ut=ct?dt.for||dt:dt&&dt.withoutSetter||ot,ht=function(e){return st(lt,e)||(lt[e]=at&&st(dt,e)?dt[e]:ut(\"Symbol.\"+e)),lt[e]},pt=L,_t=te,Et=ye,mt=ke,ft=function(e,t){var i,n;if(\"string\"===t&&Ue(i=e.toString)&&!xe(n=Me(i,e)))return n;if(Ue(i=e.valueOf)&&!xe(n=Me(i,e)))return n;if(\"string\"!==t&&Ue(i=e.toString)&&!xe(n=Me(i,e)))return n;throw Ve(\"Can't convert object to primitive value\")},gt=TypeError,Tt=ht(\"toPrimitive\"),St=function(e,t){if(!_t(e)||Et(e))return e;var i,n=mt(e,Tt);if(n){if(void 0===t&&(t=\"default\"),i=pt(n,e,t),!_t(i)||Et(i))return i;throw gt(\"Can't convert object to primitive value\")}return void 0===t&&(t=\"number\"),ft(e,t)},Rt=ye,Ct=function(e){var t=St(e,\"string\");return Rt(t)?t:t+\"\"},It=te,vt=h.document,yt=It(vt)&&It(vt.createElement),At=function(e){return yt?vt.createElement(e):{}},bt=At,wt=!N&&!n((function(){return 7!=Object.defineProperty(bt(\"div\"),\"a\",{get:function(){return 7}}).a})),Ot=N,Nt=L,Dt=k,Pt=B,Lt=Z,kt=Ct,Mt=Ze,Ut=wt,xt=Object.getOwnPropertyDescriptor;O.f=Ot?xt:function(e,t){if(e=Lt(e),t=kt(t),Ut)try{return xt(e,t)}catch(e){}if(Mt(e,t))return Pt(!Nt(Dt.f,e,t),e[t])};var Vt=n,Ft=w,Bt=/#|\\.prototype\\./,jt=function(e,t){var i=Wt[Gt(e)];return i==Kt||i!=Ht&&(Ft(t)?Vt(t):!!t)},Gt=jt.normalize=function(e){return String(e).replace(Bt,\".\").toLowerCase()},Wt=jt.data={},Ht=jt.NATIVE=\"N\",Kt=jt.POLYFILL=\"P\",Yt=jt,qt=De,zt=r,Jt=v(v.bind),Xt=function(e,t){return qt(e),void 0===t?e:zt?Jt(e,t):function(){return e.apply(t,arguments)}},Qt={},Zt=N&&n((function(){return 42!=Object.defineProperty((function(){}),\"prototype\",{value:42,writable:!1}).prototype})),$t=te,ei=String,ti=TypeError,ii=function(e){if($t(e))return e;throw ti(ei(e)+\" is not an object\")},ni=N,ri=wt,si=Zt,oi=ii,ai=Ct,ci=TypeError,di=Object.defineProperty,li=Object.getOwnPropertyDescriptor,ui=\"enumerable\",hi=\"configurable\",pi=\"writable\";Qt.f=ni?si?function(e,t,i){if(oi(e),t=ai(t),oi(i),\"function\"==typeof e&&\"prototype\"===t&&\"value\"in i&&pi in i&&!i[pi]){var n=li(e,t);n&&n[pi]&&(e[t]=i.value,i={configurable:hi in i?i[hi]:n[hi],enumerable:ui in i?i[ui]:n[ui],writable:!1})}return di(e,t,i)}:di:function(e,t,i){if(oi(e),t=ai(t),oi(i),ri)try{return di(e,t,i)}catch(e){}if(\"get\"in i||\"set\"in i)throw ci(\"Accessors not supported\");return\"value\"in i&&(e[t]=i.value),e};var _i=Qt,Ei=B,mi=N?function(e,t,i){return _i.f(e,t,Ei(1,i))}:function(e,t,i){return e[t]=i,e},fi=h,gi=f,Ti=v,Si=w,Ri=O.f,Ci=Yt,Ii=ie,vi=Xt,yi=mi,Ai=Ze,bi=function(e){var t=function(i,n,r){if(this instanceof t){switch(arguments.length){case 0:return new e;case 1:return new e(i);case 2:return new e(i,n)}return new e(i,n,r)}return gi(e,this,arguments)};return t.prototype=e.prototype,t},wi=function(e,t){var i,n,r,s,o,a,c,d,l,u=e.target,h=e.global,p=e.stat,_=e.proto,E=h?fi:p?fi[u]:(fi[u]||{}).prototype,m=h?Ii:Ii[u]||yi(Ii,u,{})[u],f=m.prototype;for(s in t)n=!(i=Ci(h?s:u+(p?\".\":\"#\")+s,e.forced))&&E&&Ai(E,s),a=m[s],n&&(c=e.dontCallGetSet?(l=Ri(E,s))&&l.value:E[s]),o=n&&c?c:t[s],n&&typeof a==typeof o||(d=e.bind&&n?vi(o,fi):e.wrap&&n?bi(o):_&&Si(o)?Ti(o):o,(e.sham||o&&o.sham||a&&a.sham)&&yi(d,\"sham\",!0),yi(m,s,d),_&&(Ai(Ii,r=u+\"Prototype\")||yi(Ii,r,{}),yi(Ii[r],s,o),e.real&&f&&(i||!f[s])&&yi(f,s,o)))},Oi=Math.ceil,Ni=Math.floor,Di=Math.trunc||function(e){var t=+e;return(t>0?Ni:Oi)(t)},Pi=function(e){var t=+e;return t!=t||0===t?0:Di(t)},Li=Pi,ki=Math.max,Mi=Math.min,Ui=function(e,t){var i=Li(e);return i<0?ki(i+t,0):Mi(i,t)},xi=Pi,Vi=Math.min,Fi=function(e){return e>0?Vi(xi(e),9007199254740991):0},Bi=function(e){return Fi(e.length)},ji=Z,Gi=Ui,Wi=Bi,Hi=function(e){return function(t,i,n){var r,s=ji(t),o=Wi(s),a=Gi(n,o);if(e&&i!=i){for(;o>a;)if((r=s[a++])!=r)return!0}else for(;o>a;a++)if((e||a in s)&&s[a]===i)return e||a||0;return!e&&-1}},Ki={includes:Hi(!0),indexOf:Hi(!1)},Yi=Ki.includes;wi({target:\"Array\",proto:!0,forced:n((function(){return!Array(1).includes()}))},{includes:function(e){return Yi(this,e,arguments.length>1?arguments[1]:void 0)}});var qi=ie,zi=function(e){return qi[e+\"Prototype\"]},Ji=zi(\"Array\").includes,Xi=te,Qi=R,Zi=ht(\"match\"),$i=function(e){var t;return Xi(e)&&(void 0!==(t=e[Zi])?!!t:\"RegExp\"==Qi(e))},en=TypeError,tn={};tn[ht(\"toStringTag\")]=\"z\";var nn=\"[object z]\"===String(tn),rn=nn,sn=w,on=R,an=ht(\"toStringTag\"),cn=Object,dn=\"Arguments\"==on(function(){return arguments}()),ln=rn?on:function(e){var t,i,n;return void 0===e?\"Undefined\":null===e?\"Null\":\"string\"==typeof(i=function(e,t){try{return e[t]}catch(e){}}(t=cn(e),an))?i:dn?on(t):\"Object\"==(n=on(t))&&sn(t.callee)?\"Arguments\":n},un=ln,hn=String,pn=function(e){if(\"Symbol\"===un(e))throw TypeError(\"Cannot convert a Symbol value to a string\");return hn(e)},_n=ht(\"match\"),En=wi,mn=function(e){if($i(e))throw en(\"The method doesn't accept regular expressions\");return e},fn=J,gn=pn,Tn=function(e){var t=/./;try{\"/./\"[e](t)}catch(i){try{return t[_n]=!1,\"/./\"[e](t)}catch(e){}}return!1},Sn=d(\"\".indexOf);En({target:\"String\",proto:!0,forced:!Tn(\"includes\")},{includes:function(e){return!!~Sn(gn(fn(this)),gn(mn(e)),arguments.length>1?arguments[1]:void 0)}});var Rn=zi(\"String\").includes,Cn=l,In=Ji,vn=Rn,yn=Array.prototype,An=String.prototype,bn=i((function(e){var t=e.includes;return e===yn||Cn(yn,e)&&t===yn.includes?In:\"string\"==typeof e||e===An||Cn(An,e)&&t===An.includes?vn:t}));let wn=!0,On=!0;function Nn(e,t,i){const n=e.match(t);return n&&n.length>=i&&parseInt(n[i],10)}function Dn(e,t,i){if(!e.RTCPeerConnection)return;const n=e.RTCPeerConnection.prototype,r=n.addEventListener;n.addEventListener=function(e,n){if(e!==t)return r.apply(this,arguments);const s=e=>{const t=i(e);t&&(n.handleEvent?n.handleEvent(t):n(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(n,s),r.apply(this,[e,s])};const s=n.removeEventListener;n.removeEventListener=function(e,i){if(e!==t||!this._eventMap||!this._eventMap[t])return s.apply(this,arguments);if(!this._eventMap[t].has(i))return s.apply(this,arguments);const n=this._eventMap[t].get(i);return this._eventMap[t].delete(i),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,s.apply(this,[e,n])},Object.defineProperty(n,\"on\"+t,{get(){return this[\"_on\"+t]},set(e){this[\"_on\"+t]&&(this.removeEventListener(t,this[\"_on\"+t]),delete this[\"_on\"+t]),e&&this.addEventListener(t,this[\"_on\"+t]=e)},enumerable:!0,configurable:!0})}function Pn(e){return\"boolean\"!=typeof e?new Error(\"Argument type: \"+typeof e+\". Please use a boolean.\"):(wn=e,e?\"adapter.js logging disabled\":\"adapter.js logging enabled\")}function Ln(e){return\"boolean\"!=typeof e?new Error(\"Argument type: \"+typeof e+\". Please use a boolean.\"):(On=!e,\"adapter.js deprecation warnings \"+(e?\"disabled\":\"enabled\"))}function kn(){if(\"object\"==typeof window){if(wn)return;\"undefined\"!=typeof console&&\"function\"==typeof console.log&&console.log.apply(console,arguments)}}function Mn(e,t){On&&console.warn(e+\" is deprecated, please use \"+t+\" instead.\")}function Un(e){return\"[object Object]\"===Object.prototype.toString.call(e)}function xn(e){return Un(e)?Object.keys(e).reduce((function(t,i){const n=Un(e[i]),r=n?xn(e[i]):e[i],s=n&&!Object.keys(r).length;return void 0===r||s?t:Object.assign(t,{[i]:r})}),{}):e}function Vn(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach((n=>{n.endsWith(\"Id\")?Vn(e,e.get(t[n]),i):n.endsWith(\"Ids\")&&t[n].forEach((t=>{Vn(e,e.get(t),i)}))})))}function Fn(e,t,i){const n=i?\"outbound-rtp\":\"inbound-rtp\",r=new Map;if(null===t)return r;const s=[];return e.forEach((e=>{\"track\"===e.type&&e.trackIdentifier===t.id&&s.push(e)})),s.forEach((t=>{e.forEach((i=>{i.type===n&&i.trackId===t.id&&Vn(e,i,r)}))})),r}const Bn=kn;function jn(e,t){const i=e&&e.navigator;if(!i.mediaDevices)return;const n=function(e){if(\"object\"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((i=>{if(\"require\"===i||\"advanced\"===i||\"mediaSource\"===i)return;const n=\"object\"==typeof e[i]?e[i]:{ideal:e[i]};void 0!==n.exact&&\"number\"==typeof n.exact&&(n.min=n.max=n.exact);const r=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):\"deviceId\"===t?\"sourceId\":t};if(void 0!==n.ideal){t.optional=t.optional||[];let e={};\"number\"==typeof n.ideal?(e[r(\"min\",i)]=n.ideal,t.optional.push(e),e={},e[r(\"max\",i)]=n.ideal,t.optional.push(e)):(e[r(\"\",i)]=n.ideal,t.optional.push(e))}void 0!==n.exact&&\"number\"!=typeof n.exact?(t.mandatory=t.mandatory||{},t.mandatory[r(\"\",i)]=n.exact):[\"min\",\"max\"].forEach((e=>{void 0!==n[e]&&(t.mandatory=t.mandatory||{},t.mandatory[r(e,i)]=n[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},r=function(e,r){if(t.version>=61)return r(e);if((e=JSON.parse(JSON.stringify(e)))&&\"object\"==typeof e.audio){const t=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,\"autoGainControl\",\"googAutoGainControl\"),t(e.audio,\"noiseSuppression\",\"googNoiseSuppression\"),e.audio=n(e.audio)}if(e&&\"object\"==typeof e.video){let s=e.video.facingMode;s=s&&(\"object\"==typeof s?s:{ideal:s});const o=t.version<66;if(s&&(\"user\"===s.exact||\"environment\"===s.exact||\"user\"===s.ideal||\"environment\"===s.ideal)&&(!i.mediaDevices.getSupportedConstraints||!i.mediaDevices.getSupportedConstraints().facingMode||o)){let t;if(delete e.video.facingMode,\"environment\"===s.exact||\"environment\"===s.ideal?t=[\"back\",\"rear\"]:\"user\"!==s.exact&&\"user\"!==s.ideal||(t=[\"front\"]),t)return i.mediaDevices.enumerateDevices().then((i=>{let o=(i=i.filter((e=>\"videoinput\"===e.kind))).find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!o&&i.length&&t.includes(\"back\")&&(o=i[i.length-1]),o&&(e.video.deviceId=s.exact?{exact:o.deviceId}:{ideal:o.deviceId}),e.video=n(e.video),Bn(\"chrome: \"+JSON.stringify(e)),r(e)}))}e.video=n(e.video)}return Bn(\"chrome: \"+JSON.stringify(e)),r(e)},s=function(e){return t.version>=64?e:{name:{PermissionDeniedError:\"NotAllowedError\",PermissionDismissedError:\"NotAllowedError\",InvalidStateError:\"NotAllowedError\",DevicesNotFoundError:\"NotFoundError\",ConstraintNotSatisfiedError:\"OverconstrainedError\",TrackStartError:\"NotReadableError\",MediaDeviceFailedDueToShutdown:\"NotAllowedError\",MediaDeviceKillSwitchOn:\"NotAllowedError\",TabCaptureError:\"AbortError\",ScreenCaptureError:\"AbortError\",DeviceCaptureError:\"AbortError\"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&\": \")+this.message}}};if(i.getUserMedia=function(e,t,n){r(e,(e=>{i.webkitGetUserMedia(e,t,(e=>{n&&n(s(e))}))}))}.bind(i),i.mediaDevices.getUserMedia){const e=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.mediaDevices.getUserMedia=function(t){return r(t,(t=>e(t).then((e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach((e=>{e.stop()})),new DOMException(\"\",\"NotFoundError\");return e}),(e=>Promise.reject(s(e))))))}}}function Gn(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function Wn(e){if(\"object\"==typeof e&&e.RTCPeerConnection&&!(\"ontrack\"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,\"ontrack\",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener(\"track\",this._ontrack),this.addEventListener(\"track\",this._ontrack=e)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener(\"addtrack\",(i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.track.id)):{track:i.track};const r=new Event(\"track\");r.track=i.track,r.receiver=n,r.transceiver={receiver:n},r.streams=[t.stream],this.dispatchEvent(r)})),t.stream.getTracks().forEach((i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.id)):{track:i};const r=new Event(\"track\");r.track=i,r.receiver=n,r.transceiver={receiver:n},r.streams=[t.stream],this.dispatchEvent(r)}))},this.addEventListener(\"addstream\",this._ontrackpoly)),t.apply(this,arguments)}}else Dn(e,\"track\",(e=>(e.transceiver||Object.defineProperty(e,\"transceiver\",{value:{receiver:e.receiver}}),e)))}function Hn(e){if(\"object\"==typeof e&&e.RTCPeerConnection&&!(\"getSenders\"in e.RTCPeerConnection.prototype)&&\"createDTMFSender\"in e.RTCPeerConnection.prototype){const t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&(\"audio\"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const i=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){let r=i.apply(this,arguments);return r||(r=t(this,e),this._senders.push(r)),r};const n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){n.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach((e=>{this._senders.push(t(this,e))}))};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],n.apply(this,[e]),e.getTracks().forEach((e=>{const t=this._senders.find((t=>t.track===e));t&&this._senders.splice(this._senders.indexOf(t),1)}))}}else if(\"object\"==typeof e&&e.RTCPeerConnection&&\"getSenders\"in e.RTCPeerConnection.prototype&&\"createDTMFSender\"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!(\"dtmf\"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e},Object.defineProperty(e.RTCRtpSender.prototype,\"dtmf\",{get(){return void 0===this._dtmf&&(\"audio\"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function Kn(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,i,n]=arguments;if(arguments.length>0&&\"function\"==typeof e)return t.apply(this,arguments);if(0===t.length&&(0===arguments.length||\"function\"!=typeof e))return t.apply(this,[]);const r=function(e){const t={};return e.result().forEach((e=>{const i={id:e.id,timestamp:e.timestamp,type:{localcandidate:\"local-candidate\",remotecandidate:\"remote-candidate\"}[e.type]||e.type};e.names().forEach((t=>{i[t]=e.stat(t)})),t[i.id]=i})),t},s=function(e){return new Map(Object.keys(e).map((t=>[t,e[t]])))};if(arguments.length>=2){const n=function(e){i(s(r(e)))};return t.apply(this,[n,e])}return new Promise(((e,i)=>{t.apply(this,[function(t){e(s(r(t)))},i])})).then(i,n)}}function Yn(e){if(!(\"object\"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!(\"getStats\"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>Fn(t,e.track,!0)))}}if(!(\"getStats\"in e.RTCRtpReceiver.prototype)){const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),Dn(e,\"track\",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>Fn(t,e.track,!1)))}}if(!(\"getStats\"in e.RTCRtpSender.prototype)||!(\"getStats\"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,i,n;return this.getSenders().forEach((i=>{i.track===e&&(t?n=!0:t=i)})),this.getReceivers().forEach((t=>(t.track===e&&(i?n=!0:i=t),t.track===e))),n||t&&i?Promise.reject(new DOMException(\"There are more than one sender or receiver for the track.\",\"InvalidAccessError\")):t?t.getStats():i?i.getStats():Promise.reject(new DOMException(\"There is no sender or receiver for the track.\",\"InvalidAccessError\"))}return t.apply(this,arguments)}}function qn(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((e=>this._shimmedLocalStreams[e][0]))};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){if(!i)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const n=t.apply(this,arguments);return this._shimmedLocalStreams[i.id]?-1===this._shimmedLocalStreams[i.id].indexOf(n)&&this._shimmedLocalStreams[i.id].push(n):this._shimmedLocalStreams[i.id]=[i,n],n};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException(\"Track already exists.\",\"InvalidAccessError\")}));const t=this.getSenders();i.apply(this,arguments);const n=this.getSenders().filter((e=>-1===t.indexOf(e)));this._shimmedLocalStreams[e.id]=[e].concat(n)};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],n.apply(this,arguments)};const r=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((t=>{const i=this._shimmedLocalStreams[t].indexOf(e);-1!==i&&this._shimmedLocalStreams[t].splice(i,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]})),r.apply(this,arguments)}}function zn(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return qn(e);const i=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=i.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map((e=>this._reverseStreams[e.id]))};const n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException(\"Track already exists.\",\"InvalidAccessError\")})),!this._reverseStreams[t.id]){const i=new e.MediaStream(t.getTracks());this._streams[t.id]=i,this._reverseStreams[i.id]=t,t=i}n.apply(this,[t])};const r=e.RTCPeerConnection.prototype.removeStream;function s(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],r=e._streams[n.id];i=i.replace(new RegExp(r.id,\"g\"),n.id)})),new RTCSessionDescription({type:t.type,sdp:i})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},r.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,i){if(\"closed\"===this.signalingState)throw new DOMException(\"The RTCPeerConnection's signalingState is 'closed'.\",\"InvalidStateError\");const n=[].slice.call(arguments,1);if(1!==n.length||!n[0].getTracks().find((e=>e===t)))throw new DOMException(\"The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.\",\"NotSupportedError\");if(this.getSenders().find((e=>e.track===t)))throw new DOMException(\"Track already exists.\",\"InvalidAccessError\");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const r=this._streams[i.id];if(r)r.addTrack(t),Promise.resolve().then((()=>{this.dispatchEvent(new Event(\"negotiationneeded\"))}));else{const n=new e.MediaStream([t]);this._streams[i.id]=n,this._reverseStreams[n.id]=i,this.addStream(n)}return this.getSenders().find((e=>e.track===t))},[\"createOffer\",\"createAnswer\"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){const e=arguments;return arguments.length&&\"function\"==typeof arguments[0]?i.apply(this,[t=>{const i=s(this,t);e[0].apply(null,[i])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):i.apply(this,arguments).then((e=>s(this,e)))}};e.RTCPeerConnection.prototype[t]=n[t]}));const o=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],r=e._streams[n.id];i=i.replace(new RegExp(n.id,\"g\"),r.id)})),new RTCSessionDescription({type:t.type,sdp:i})}(this,arguments[0]),o.apply(this,arguments)):o.apply(this,arguments)};const a=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,\"localDescription\");Object.defineProperty(e.RTCPeerConnection.prototype,\"localDescription\",{get(){const e=a.get.apply(this);return\"\"===e.type?e:s(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if(\"closed\"===this.signalingState)throw new DOMException(\"The RTCPeerConnection's signalingState is 'closed'.\",\"InvalidStateError\");if(!e._pc)throw new DOMException(\"Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.\",\"TypeError\");if(!(e._pc===this))throw new DOMException(\"Sender was not created by this connection.\",\"InvalidAccessError\");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach((i=>{this._streams[i].getTracks().find((t=>e.track===t))&&(t=this._streams[i])})),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event(\"negotiationneeded\")))}}function Jn(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&[\"setLocalDescription\",\"setRemoteDescription\",\"addIceCandidate\"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new(\"addIceCandidate\"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]}))}function Xn(e,t){Dn(e,\"negotiationneeded\",(e=>{const i=e.target;if(!(t.version<72||i.getConfiguration&&\"plan-b\"===i.getConfiguration().sdpSemantics)||\"stable\"===i.signalingState)return e}))}var Qn=Object.freeze({__proto__:null,fixNegotiationNeeded:Xn,shimAddTrackRemoveTrack:zn,shimAddTrackRemoveTrackWithNative:qn,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&\"getDisplayMedia\"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(\"function\"==typeof t?e.navigator.mediaDevices.getDisplayMedia=function(i){return t(i).then((t=>{const n=i.video&&i.video.width,r=i.video&&i.video.height,s=i.video&&i.video.frameRate;return i.video={mandatory:{chromeMediaSource:\"desktop\",chromeMediaSourceId:t,maxFrameRate:s||3}},n&&(i.video.mandatory.maxWidth=n),r&&(i.video.mandatory.maxHeight=r),e.navigator.mediaDevices.getUserMedia(i)}))}:console.error(\"shimGetDisplayMedia: getSourceId argument is not a function\"))},shimGetSendersWithDtmf:Hn,shimGetStats:Kn,shimGetUserMedia:jn,shimMediaStream:Gn,shimOnTrack:Wn,shimPeerConnection:Jn,shimSenderReceiverGetStats:Yn});function Zn(e,t){const i=e&&e.navigator,n=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,n){Mn(\"navigator.getUserMedia\",\"navigator.mediaDevices.getUserMedia\"),i.mediaDevices.getUserMedia(e).then(t,n)},!(t.version>55&&\"autoGainControl\"in i.mediaDevices.getSupportedConstraints())){const e=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])},t=i.mediaDevices.getUserMedia.bind(i.mediaDevices);if(i.mediaDevices.getUserMedia=function(i){return\"object\"==typeof i&&\"object\"==typeof i.audio&&(i=JSON.parse(JSON.stringify(i)),e(i.audio,\"autoGainControl\",\"mozAutoGainControl\"),e(i.audio,\"noiseSuppression\",\"mozNoiseSuppression\")),t(i)},n&&n.prototype.getSettings){const t=n.prototype.getSettings;n.prototype.getSettings=function(){const i=t.apply(this,arguments);return e(i,\"mozAutoGainControl\",\"autoGainControl\"),e(i,\"mozNoiseSuppression\",\"noiseSuppression\"),i}}if(n&&n.prototype.applyConstraints){const t=n.prototype.applyConstraints;n.prototype.applyConstraints=function(i){return\"audio\"===this.kind&&\"object\"==typeof i&&(i=JSON.parse(JSON.stringify(i)),e(i,\"autoGainControl\",\"mozAutoGainControl\"),e(i,\"noiseSuppression\",\"mozNoiseSuppression\")),t.apply(this,[i])}}}}function $n(e){\"object\"==typeof e&&e.RTCTrackEvent&&\"receiver\"in e.RTCTrackEvent.prototype&&!(\"transceiver\"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,\"transceiver\",{get(){return{receiver:this.receiver}}})}function er(e,t){if(\"object\"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&[\"setLocalDescription\",\"setRemoteDescription\",\"addIceCandidate\"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new(\"addIceCandidate\"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]}));const i={inboundrtp:\"inbound-rtp\",outboundrtp:\"outbound-rtp\",candidatepair:\"candidate-pair\",localcandidate:\"local-candidate\",remotecandidate:\"remote-candidate\"},n=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,r,s]=arguments;return n.apply(this,[e||null]).then((e=>{if(t.version<53&&!r)try{e.forEach((e=>{e.type=i[e.type]||e.type}))}catch(t){if(\"TypeError\"!==t.name)throw t;e.forEach(((t,n)=>{e.set(n,Object.assign({},t,{type:i[t.type]||t.type}))}))}return e})).then(r,s)}}function tr(e){if(\"object\"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&\"getStats\"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function ir(e){if(\"object\"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&\"getStats\"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),Dn(e,\"track\",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function nr(e){e.RTCPeerConnection&&!(\"removeStream\"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){Mn(\"removeStream\",\"removeTrack\"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function rr(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function sr(e){if(\"object\"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]),e=[...e];const i=e.length>0;i&&e.forEach((e=>{if(\"rid\"in e){if(!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError(\"Invalid RID value provided.\")}if(\"scaleResolutionDownBy\"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError(\"scale_resolution_down_by must be >= 1.0\");if(\"maxFramerate\"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError(\"max_framerate must be >= 0.0\")}));const n=t.apply(this,arguments);if(i){const{sender:t}=n,i=t.getParameters();(!(\"encodings\"in i)||1===i.encodings.length&&0===Object.keys(i.encodings[0]).length)&&(i.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(i).then((()=>{delete t.sendEncodings})).catch((()=>{delete t.sendEncodings}))))}return n})}function or(e){if(\"object\"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const e=t.apply(this,arguments);return\"encodings\"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function ar(e){if(\"object\"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}function cr(e){if(\"object\"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}var dr=Object.freeze({__proto__:null,shimAddTransceiver:sr,shimCreateAnswer:cr,shimCreateOffer:ar,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&\"getDisplayMedia\"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(i){if(!i||!i.video){const e=new DOMException(\"getDisplayMedia without video constraints is undefined\");return e.name=\"NotFoundError\",e.code=8,Promise.reject(e)}return!0===i.video?i.video={mediaSource:t}:i.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(i)})},shimGetParameters:or,shimGetUserMedia:Zn,shimOnTrack:$n,shimPeerConnection:er,shimRTCDataChannel:rr,shimReceiverGetStats:ir,shimRemoveStream:nr,shimSenderGetStats:tr});function lr(e){if(\"object\"==typeof e&&e.RTCPeerConnection){if(\"getLocalStreams\"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!(\"addStream\"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach((i=>t.call(this,i,e))),e.getVideoTracks().forEach((i=>t.call(this,i,e)))},e.RTCPeerConnection.prototype.addTrack=function(e,...i){return i&&i.forEach((e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]})),t.apply(this,arguments)}}\"removeStream\"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const i=e.getTracks();this.getSenders().forEach((e=>{i.includes(e.track)&&this.removeTrack(e)}))})}}function ur(e){if(\"object\"==typeof e&&e.RTCPeerConnection&&(\"getRemoteStreams\"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!(\"onaddstream\"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,\"onaddstream\",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener(\"addstream\",this._onaddstream),this.removeEventListener(\"track\",this._onaddstreampoly)),this.addEventListener(\"addstream\",this._onaddstream=e),this.addEventListener(\"track\",this._onaddstreampoly=e=>{e.streams.forEach((e=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);const t=new Event(\"addstream\");t.stream=e,this.dispatchEvent(t)}))})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const e=this;return this._onaddstreampoly||this.addEventListener(\"track\",this._onaddstreampoly=function(t){t.streams.forEach((t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);const i=new Event(\"addstream\");i.stream=t,e.dispatchEvent(i)}))}),t.apply(e,arguments)}}}function hr(e){if(\"object\"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,i=t.createOffer,n=t.createAnswer,r=t.setLocalDescription,s=t.setRemoteDescription,o=t.addIceCandidate;t.createOffer=function(e,t){const n=arguments.length>=2?arguments[2]:arguments[0],r=i.apply(this,[n]);return t?(r.then(e,t),Promise.resolve()):r},t.createAnswer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],r=n.apply(this,[i]);return t?(r.then(e,t),Promise.resolve()):r};let a=function(e,t,i){const n=r.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n};t.setLocalDescription=a,a=function(e,t,i){const n=s.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.setRemoteDescription=a,a=function(e,t,i){const n=o.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.addIceCandidate=a}function pr(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,i=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>i(_r(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,i,n){t.mediaDevices.getUserMedia(e).then(i,n)}.bind(t))}function _r(e){return e&&void 0!==e.video?Object.assign({},e,{video:xn(e.video)}):e}function Er(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,i){if(e&&e.iceServers){const t=[];for(let i=0;it.generateCertificate})}function mr(e){\"object\"==typeof e&&e.RTCTrackEvent&&\"receiver\"in e.RTCTrackEvent.prototype&&!(\"transceiver\"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,\"transceiver\",{get(){return{receiver:this.receiver}}})}function fr(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);const t=this.getTransceivers().find((e=>\"audio\"===e.receiver.track.kind));!1===e.offerToReceiveAudio&&t?\"sendrecv\"===t.direction?t.setDirection?t.setDirection(\"sendonly\"):t.direction=\"sendonly\":\"recvonly\"===t.direction&&(t.setDirection?t.setDirection(\"inactive\"):t.direction=\"inactive\"):!0!==e.offerToReceiveAudio||t||this.addTransceiver(\"audio\",{direction:\"recvonly\"}),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);const i=this.getTransceivers().find((e=>\"video\"===e.receiver.track.kind));!1===e.offerToReceiveVideo&&i?\"sendrecv\"===i.direction?i.setDirection?i.setDirection(\"sendonly\"):i.direction=\"sendonly\":\"recvonly\"===i.direction&&(i.setDirection?i.setDirection(\"inactive\"):i.direction=\"inactive\"):!0!==e.offerToReceiveVideo||i||this.addTransceiver(\"video\",{direction:\"recvonly\"})}return t.apply(this,arguments)}}function gr(e){\"object\"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var Tr=Object.freeze({__proto__:null,shimAudioContext:gr,shimCallbacksAPI:hr,shimConstraints:_r,shimCreateOfferLegacy:fr,shimGetUserMedia:pr,shimLocalStreamsAPI:lr,shimRTCIceServerUrls:Er,shimRemoteStreamsAPI:ur,shimTrackEventTransceiver:mr}),Sr={exports:{}};!function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split(\"\\n\").map((e=>e.trim()))},t.splitSections=function(e){return e.split(\"\\nm=\").map(((e,t)=>(t>0?\"m=\"+e:e).trim()+\"\\r\\n\"))},t.getDescription=function(e){const i=t.splitSections(e);return i&&i[0]},t.getMediaSections=function(e){const i=t.splitSections(e);return i.shift(),i},t.matchPrefix=function(e,i){return t.splitLines(e).filter((e=>0===e.indexOf(i)))},t.parseCandidate=function(e){let t;t=0===e.indexOf(\"a=candidate:\")?e.substring(12).split(\" \"):e.substring(10).split(\" \");const i={foundation:t[0],component:{1:\"rtp\",2:\"rtcp\"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let e=8;e0?t[0].split(\"/\")[1]:\"sendrecv\",uri:t[1],attributes:t.slice(2).join(\" \")}},t.writeExtmap=function(e){return\"a=extmap:\"+(e.id||e.preferredId)+(e.direction&&\"sendrecv\"!==e.direction?\"/\"+e.direction:\"\")+\" \"+e.uri+(e.attributes?\" \"+e.attributes:\"\")+\"\\r\\n\"},t.parseFmtp=function(e){const t={};let i;const n=e.substring(e.indexOf(\" \")+1).split(\";\");for(let e=0;e{void 0!==e.parameters[t]?n.push(t+\"=\"+e.parameters[t]):n.push(t)})),t+=\"a=fmtp:\"+i+\" \"+n.join(\";\")+\"\\r\\n\"}return t},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(\" \")+1).split(\" \");return{type:t.shift(),parameter:t.join(\" \")}},t.writeRtcpFb=function(e){let t=\"\",i=e.payloadType;return void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((e=>{t+=\"a=rtcp-fb:\"+i+\" \"+e.type+(e.parameter&&e.parameter.length?\" \"+e.parameter:\"\")+\"\\r\\n\"})),t},t.parseSsrcMedia=function(e){const t=e.indexOf(\" \"),i={ssrc:parseInt(e.substring(7,t),10)},n=e.indexOf(\":\",t);return n>-1?(i.attribute=e.substring(t+1,n),i.value=e.substring(n+1)):i.attribute=e.substring(t+1),i},t.parseSsrcGroup=function(e){const t=e.substring(13).split(\" \");return{semantics:t.shift(),ssrcs:t.map((e=>parseInt(e,10)))}},t.getMid=function(e){const i=t.matchPrefix(e,\"a=mid:\")[0];if(i)return i.substring(6)},t.parseFingerprint=function(e){const t=e.substring(14).split(\" \");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,i){return{role:\"auto\",fingerprints:t.matchPrefix(e+i,\"a=fingerprint:\").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let i=\"a=setup:\"+t+\"\\r\\n\";return e.fingerprints.forEach((e=>{i+=\"a=fingerprint:\"+e.algorithm+\" \"+e.value+\"\\r\\n\"})),i},t.parseCryptoLine=function(e){const t=e.substring(9).split(\" \");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return\"a=crypto:\"+e.tag+\" \"+e.cryptoSuite+\" \"+(\"object\"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?\" \"+e.sessionParams.join(\" \"):\"\")+\"\\r\\n\"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf(\"inline:\"))return null;const t=e.substring(7).split(\"|\");return{keyMethod:\"inline\",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(\":\")[0]:void 0,mkiLength:t[2]?t[2].split(\":\")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+\":\"+e.keySalt+(e.lifeTime?\"|\"+e.lifeTime:\"\")+(e.mkiValue&&e.mkiLength?\"|\"+e.mkiValue+\":\"+e.mkiLength:\"\")},t.getCryptoParameters=function(e,i){return t.matchPrefix(e+i,\"a=crypto:\").map(t.parseCryptoLine)},t.getIceParameters=function(e,i){const n=t.matchPrefix(e+i,\"a=ice-ufrag:\")[0],r=t.matchPrefix(e+i,\"a=ice-pwd:\")[0];return n&&r?{usernameFragment:n.substring(12),password:r.substring(10)}:null},t.writeIceParameters=function(e){let t=\"a=ice-ufrag:\"+e.usernameFragment+\"\\r\\na=ice-pwd:\"+e.password+\"\\r\\n\";return e.iceLite&&(t+=\"a=ice-lite\\r\\n\"),t},t.parseRtpParameters=function(e){const i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},n=t.splitLines(e)[0].split(\" \");i.profile=n[2];for(let r=3;r{i.headerExtensions.push(t.parseExtmap(e))}));const r=t.matchPrefix(e,\"a=rtcp-fb:* \").map(t.parseRtcpFb);return i.codecs.forEach((e=>{r.forEach((t=>{e.rtcpFeedback.find((e=>e.type===t.type&&e.parameter===t.parameter))||e.rtcpFeedback.push(t)}))})),i},t.writeRtpDescription=function(e,i){let n=\"\";n+=\"m=\"+e+\" \",n+=i.codecs.length>0?\"9\":\"0\",n+=\" \"+(i.profile||\"UDP/TLS/RTP/SAVPF\")+\" \",n+=i.codecs.map((e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType)).join(\" \")+\"\\r\\n\",n+=\"c=IN IP4 0.0.0.0\\r\\n\",n+=\"a=rtcp:9 IN IP4 0.0.0.0\\r\\n\",i.codecs.forEach((e=>{n+=t.writeRtpMap(e),n+=t.writeFmtp(e),n+=t.writeRtcpFb(e)}));let r=0;return i.codecs.forEach((e=>{e.maxptime>r&&(r=e.maxptime)})),r>0&&(n+=\"a=maxptime:\"+r+\"\\r\\n\"),i.headerExtensions&&i.headerExtensions.forEach((e=>{n+=t.writeExtmap(e)})),n},t.parseRtpEncodingParameters=function(e){const i=[],n=t.parseRtpParameters(e),r=-1!==n.fecMechanisms.indexOf(\"RED\"),s=-1!==n.fecMechanisms.indexOf(\"ULPFEC\"),o=t.matchPrefix(e,\"a=ssrc:\").map((e=>t.parseSsrcMedia(e))).filter((e=>\"cname\"===e.attribute)),a=o.length>0&&o[0].ssrc;let c;const d=t.matchPrefix(e,\"a=ssrc-group:FID\").map((e=>e.substring(17).split(\" \").map((e=>parseInt(e,10)))));d.length>0&&d[0].length>1&&d[0][0]===a&&(c=d[0][1]),n.codecs.forEach((e=>{if(\"RTX\"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:a,codecPayloadType:parseInt(e.parameters.apt,10)};a&&c&&(t.rtx={ssrc:c}),i.push(t),r&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:a,mechanism:s?\"red+ulpfec\":\"red\"},i.push(t))}})),0===i.length&&a&&i.push({ssrc:a});let l=t.matchPrefix(e,\"b=\");return l.length&&(l=0===l[0].indexOf(\"b=TIAS:\")?parseInt(l[0].substring(7),10):0===l[0].indexOf(\"b=AS:\")?1e3*parseInt(l[0].substring(5),10)*.95-16e3:void 0,i.forEach((e=>{e.maxBitrate=l}))),i},t.parseRtcpParameters=function(e){const i={},n=t.matchPrefix(e,\"a=ssrc:\").map((e=>t.parseSsrcMedia(e))).filter((e=>\"cname\"===e.attribute))[0];n&&(i.cname=n.value,i.ssrc=n.ssrc);const r=t.matchPrefix(e,\"a=rtcp-rsize\");i.reducedSize=r.length>0,i.compound=0===r.length;const s=t.matchPrefix(e,\"a=rtcp-mux\");return i.mux=s.length>0,i},t.writeRtcpParameters=function(e){let t=\"\";return e.reducedSize&&(t+=\"a=rtcp-rsize\\r\\n\"),e.mux&&(t+=\"a=rtcp-mux\\r\\n\"),void 0!==e.ssrc&&e.cname&&(t+=\"a=ssrc:\"+e.ssrc+\" cname:\"+e.cname+\"\\r\\n\"),t},t.parseMsid=function(e){let i;const n=t.matchPrefix(e,\"a=msid:\");if(1===n.length)return i=n[0].substring(7).split(\" \"),{stream:i[0],track:i[1]};const r=t.matchPrefix(e,\"a=ssrc:\").map((e=>t.parseSsrcMedia(e))).filter((e=>\"msid\"===e.attribute));return r.length>0?(i=r[0].value.split(\" \"),{stream:i[0],track:i[1]}):void 0},t.parseSctpDescription=function(e){const i=t.parseMLine(e),n=t.matchPrefix(e,\"a=max-message-size:\");let r;n.length>0&&(r=parseInt(n[0].substring(19),10)),isNaN(r)&&(r=65536);const s=t.matchPrefix(e,\"a=sctp-port:\");if(s.length>0)return{port:parseInt(s[0].substring(12),10),protocol:i.fmt,maxMessageSize:r};const o=t.matchPrefix(e,\"a=sctpmap:\");if(o.length>0){const e=o[0].substring(10).split(\" \");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:r}}},t.writeSctpDescription=function(e,t){let i=[];return i=\"DTLS/SCTP\"!==e.protocol?[\"m=\"+e.kind+\" 9 \"+e.protocol+\" \"+t.protocol+\"\\r\\n\",\"c=IN IP4 0.0.0.0\\r\\n\",\"a=sctp-port:\"+t.port+\"\\r\\n\"]:[\"m=\"+e.kind+\" 9 \"+e.protocol+\" \"+t.port+\"\\r\\n\",\"c=IN IP4 0.0.0.0\\r\\n\",\"a=sctpmap:\"+t.port+\" \"+t.protocol+\" 65535\\r\\n\"],void 0!==t.maxMessageSize&&i.push(\"a=max-message-size:\"+t.maxMessageSize+\"\\r\\n\"),i.join(\"\")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,i,n){let r;const s=void 0!==i?i:2;r=e||t.generateSessionId();return\"v=0\\r\\no=\"+(n||\"thisisadapterortc\")+\" \"+r+\" \"+s+\" IN IP4 127.0.0.1\\r\\ns=-\\r\\nt=0 0\\r\\n\"},t.getDirection=function(e,i){const n=t.splitLines(e);for(let e=0;e(t.candidate&&Object.defineProperty(t,\"candidate\",{value:new e.RTCIceCandidate(t.candidate),writable:\"false\"}),t)))}function yr(e){!e.RTCIceCandidate||e.RTCIceCandidate&&\"relayProtocol\"in e.RTCIceCandidate.prototype||Dn(e,\"icecandidate\",(e=>{if(e.candidate){const t=Cr.parseCandidate(e.candidate.candidate);\"relay\"===t.type&&(e.candidate.relayProtocol={0:\"tls\",1:\"tcp\",2:\"udp\"}[t.priority>>24])}return e}))}function Ar(e,t){if(!e.RTCPeerConnection)return;\"sctp\"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,\"sctp\",{get(){return void 0===this._sctp?null:this._sctp}});const i=function(e){if(!e||!e.sdp)return!1;const t=Cr.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=Cr.parseMLine(e);return t&&\"application\"===t.kind&&-1!==t.protocol.indexOf(\"SCTP\")}))},n=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\\d+)/);if(null===t||t.length<2)return-1;const i=parseInt(t[1],10);return i!=i?-1:i},r=function(e){let i=65536;return\"firefox\"===t.browser&&(i=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),i},s=function(e,i){let n=65536;\"firefox\"===t.browser&&57===t.version&&(n=65535);const r=Cr.matchPrefix(e.sdp,\"a=max-message-size:\");return r.length>0?n=parseInt(r[0].substr(19),10):\"firefox\"===t.browser&&-1!==i&&(n=2147483637),n},o=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,\"chrome\"===t.browser&&t.version>=76){const{sdpSemantics:e}=this.getConfiguration();\"plan-b\"===e&&Object.defineProperty(this,\"sctp\",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(i(arguments[0])){const e=n(arguments[0]),t=r(e),i=s(arguments[0],e);let o;o=0===t&&0===i?Number.POSITIVE_INFINITY:0===t||0===i?Math.max(t,i):Math.min(t,i);const a={};Object.defineProperty(a,\"maxMessageSize\",{get:()=>o}),this._sctp=a}return o.apply(this,arguments)}}function br(e){if(!e.RTCPeerConnection||!(\"createDataChannel\"in e.RTCPeerConnection.prototype))return;function t(e,t){const i=e.send;e.send=function(){const n=arguments[0],r=n.length||n.size||n.byteLength;if(\"open\"===e.readyState&&t.sctp&&r>t.sctp.maxMessageSize)throw new TypeError(\"Message too large (can send a maximum of \"+t.sctp.maxMessageSize+\" bytes)\");return i.apply(e,arguments)}}const i=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=i.apply(this,arguments);return t(e,this),e},Dn(e,\"datachannel\",(e=>(t(e.channel,e.target),e)))}function wr(e){if(!e.RTCPeerConnection||\"connectionState\"in e.RTCPeerConnection.prototype)return;const t=e.RTCPeerConnection.prototype;Object.defineProperty(t,\"connectionState\",{get(){return{completed:\"connected\",checking:\"connecting\"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,\"onconnectionstatechange\",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener(\"connectionstatechange\",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener(\"connectionstatechange\",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),[\"setLocalDescription\",\"setRemoteDescription\"].forEach((e=>{const i=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{const t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;const i=new Event(\"connectionstatechange\",e);t.dispatchEvent(i)}return e},this.addEventListener(\"iceconnectionstatechange\",this._connectionstatechangepoly)),i.apply(this,arguments)}}))}function Or(e,t){if(!e.RTCPeerConnection)return;if(\"chrome\"===t.browser&&t.version>=71)return;if(\"safari\"===t.browser&&t.version>=605)return;const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf(\"\\na=extmap-allow-mixed\")){const i=t.sdp.split(\"\\n\").filter((e=>\"a=extmap-allow-mixed\"!==e.trim())).join(\"\\n\");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:i}):t.sdp=i}return i.apply(this,arguments)}}function Nr(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.addIceCandidate;i&&0!==i.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(\"chrome\"===t.browser&&t.version<78||\"firefox\"===t.browser&&t.version<68||\"safari\"===t.browser)&&arguments[0]&&\"\"===arguments[0].candidate?Promise.resolve():i.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function Dr(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.setLocalDescription;i&&0!==i.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if(\"object\"!=typeof e||e.type&&e.sdp)return i.apply(this,arguments);if(e={type:e.type,sdp:e.sdp},!e.type)switch(this.signalingState){case\"stable\":case\"have-local-offer\":case\"have-remote-pranswer\":e.type=\"offer\";break;default:e.type=\"answer\"}if(e.sdp||\"offer\"!==e.type&&\"answer\"!==e.type)return i.apply(this,[e]);return(\"offer\"===e.type?this.createOffer:this.createAnswer).apply(this).then((e=>i.apply(this,[e])))})}var Pr=Object.freeze({__proto__:null,removeExtmapAllowMixed:Or,shimAddIceCandidateNullOrEmpty:Nr,shimConnectionState:wr,shimMaxMessageSize:Ar,shimParameterlessSetLocalDescription:Dr,shimRTCIceCandidate:vr,shimRTCIceCandidateRelayProtocol:yr,shimSendThrowTypeError:br});!function({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const i=kn,n=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator)return t.browser=\"Not a browser.\",t;const{navigator:i}=e;if(i.mozGetUserMedia)t.browser=\"firefox\",t.version=Nn(i.userAgent,/Firefox\\/(\\d+)\\./,1);else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser=\"chrome\",t.version=Nn(i.userAgent,/Chrom(e|ium)\\/(\\d+)\\./,2);else{if(!e.RTCPeerConnection||!i.userAgent.match(/AppleWebKit\\/(\\d+)\\./))return t.browser=\"Not a supported browser.\",t;t.browser=\"safari\",t.version=Nn(i.userAgent,/AppleWebKit\\/(\\d+)\\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&\"currentDirection\"in e.RTCRtpTransceiver.prototype}return t}(e),r={browserDetails:n,commonShim:Pr,extractVersion:Nn,disableLog:Pn,disableWarnings:Ln,sdp:Ir};switch(n.browser){case\"chrome\":if(!Qn||!Jn||!t.shimChrome)return i(\"Chrome shim is not included in this adapter release.\"),r;if(null===n.version)return i(\"Chrome shim can not determine version, not shimming.\"),r;i(\"adapter.js shimming chrome.\"),r.browserShim=Qn,Nr(e,n),Dr(e),jn(e,n),Gn(e),Jn(e,n),Wn(e),zn(e,n),Hn(e),Kn(e),Yn(e),Xn(e,n),vr(e),yr(e),wr(e),Ar(e,n),br(e),Or(e,n);break;case\"firefox\":if(!dr||!er||!t.shimFirefox)return i(\"Firefox shim is not included in this adapter release.\"),r;i(\"adapter.js shimming firefox.\"),r.browserShim=dr,Nr(e,n),Dr(e),Zn(e,n),er(e,n),$n(e),nr(e),tr(e),ir(e),rr(e),sr(e),or(e),ar(e),cr(e),vr(e),wr(e),Ar(e,n),br(e);break;case\"safari\":if(!Tr||!t.shimSafari)return i(\"Safari shim is not included in this adapter release.\"),r;i(\"adapter.js shimming safari.\"),r.browserShim=Tr,Nr(e,n),Dr(e),Er(e),fr(e),hr(e),lr(e),ur(e),mr(e),pr(e),gr(e),vr(e),yr(e),Ar(e,n),br(e),Or(e,n);break;default:i(\"Unsupported browser!\")}}({window:\"undefined\"==typeof window?void 0:window});var Lr={exports:{}},kr=wi,Mr=N,Ur=Qt.f;kr({target:\"Object\",stat:!0,forced:Object.defineProperty!==Ur,sham:!Mr},{defineProperty:Ur});var xr=ie.Object,Vr=Lr.exports=function(e,t,i){return xr.defineProperty(e,t,i)};xr.defineProperty.sham&&(Vr.sham=!0);var Fr=i(Lr.exports),Br=R,jr=Array.isArray||function(e){return\"Array\"==Br(e)},Gr=TypeError,Wr=Ct,Hr=Qt,Kr=B,Yr=function(e,t,i){var n=Wr(t);n in e?Hr.f(e,n,Kr(0,i)):e[n]=i},qr=w,zr=He,Jr=d(Function.toString);qr(zr.inspectSource)||(zr.inspectSource=function(e){return Jr(e)});var Xr=zr.inspectSource,Qr=d,Zr=n,$r=w,es=ln,ts=Xr,is=function(){},ns=[],rs=ae(\"Reflect\",\"construct\"),ss=/^\\s*(?:class|function)\\b/,os=Qr(ss.exec),as=!ss.exec(is),cs=function(e){if(!$r(e))return!1;try{return rs(is,ns,e),!0}catch(e){return!1}},ds=function(e){if(!$r(e))return!1;switch(es(e)){case\"AsyncFunction\":case\"GeneratorFunction\":case\"AsyncGeneratorFunction\":return!1}try{return as||!!os(ss,ts(e))}catch(e){return!0}};ds.sham=!0;var ls=!rs||Zr((function(){var e;return cs(cs.call)||!cs(Object)||!cs((function(){e=!0}))||e}))?ds:cs,us=jr,hs=ls,ps=te,_s=ht(\"species\"),Es=Array,ms=function(e){var t;return us(e)&&(t=e.constructor,(hs(t)&&(t===Es||us(t.prototype))||ps(t)&&null===(t=t[_s]))&&(t=void 0)),void 0===t?Es:t},fs=function(e,t){return new(ms(e))(0===t?0:t)},gs=n,Ts=Ee,Ss=ht(\"species\"),Rs=wi,Cs=n,Is=jr,vs=te,ys=Je,As=Bi,bs=function(e){if(e>9007199254740991)throw Gr(\"Maximum allowed index exceeded\");return e},ws=Yr,Os=fs,Ns=function(e){return Ts>=51||!gs((function(){var t=[];return(t.constructor={})[Ss]=function(){return{foo:1}},1!==t[e](Boolean).foo}))},Ds=Ee,Ps=ht(\"isConcatSpreadable\"),Ls=Ds>=51||!Cs((function(){var e=[];return e[Ps]=!1,e.concat()[0]!==e})),ks=function(e){if(!vs(e))return!1;var t=e[Ps];return void 0!==t?!!t:Is(e)};Rs({target:\"Array\",proto:!0,arity:1,forced:!Ls||!Ns(\"concat\")},{concat:function(e){var t,i,n,r,s,o=ys(this),a=Os(o,0),c=0;for(t=-1,n=arguments.length;tr;)xs(n,i=t[r++])&&(~Fs(s,i)||js(s,i));return s},Ws=[\"constructor\",\"hasOwnProperty\",\"isPrototypeOf\",\"propertyIsEnumerable\",\"toLocaleString\",\"toString\",\"valueOf\"],Hs=Gs,Ks=Ws,Ys=Object.keys||function(e){return Hs(e,Ks)},qs=N,zs=Zt,Js=Qt,Xs=ii,Qs=Z,Zs=Ys;Ms.f=qs&&!zs?Object.defineProperties:function(e,t){Xs(e);for(var i,n=Qs(t),r=Zs(t),s=r.length,o=0;s>o;)Js.f(e,i=r[o++],n[i]);return e};var $s,eo=ae(\"document\",\"documentElement\"),to=nt,io=Ye(\"keys\"),no=function(e){return io[e]||(io[e]=to(e))},ro=ii,so=Ms,oo=Ws,ao=Us,co=eo,lo=At,uo=\"prototype\",ho=\"script\",po=no(\"IE_PROTO\"),_o=function(){},Eo=function(e){return\"<\"+ho+\">\"+e+\"\"},mo=function(e){e.write(Eo(\"\")),e.close();var t=e.parentWindow.Object;return e=null,t},fo=function(){try{$s=new ActiveXObject(\"htmlfile\")}catch(e){}var e,t,i;fo=\"undefined\"!=typeof document?document.domain&&$s?mo($s):(t=lo(\"iframe\"),i=\"java\"+ho+\":\",t.style.display=\"none\",co.appendChild(t),t.src=String(i),(e=t.contentWindow.document).open(),e.write(Eo(\"document.F=Object\")),e.close(),e.F):mo($s);for(var n=oo.length;n--;)delete fo[uo][oo[n]];return fo()};ao[po]=!0;var go=Object.create||function(e,t){var i;return null!==e?(_o[uo]=ro(e),i=new _o,_o[uo]=null,i[po]=e):i=fo(),void 0===t?i:so.f(i,t)},To={},So=Gs,Ro=Ws.concat(\"length\",\"prototype\");To.f=Object.getOwnPropertyNames||function(e){return So(e,Ro)};var Co={},Io=Ui,vo=Bi,yo=Yr,Ao=Array,bo=Math.max,wo=function(e,t,i){for(var n=vo(e),r=Io(t,n),s=Io(void 0===i?n:i,n),o=Ao(bo(s-r,0)),a=0;rg;g++)if((a||g in E)&&(p=m(h=E[g],g,_),e))if(t)S[g]=p;else if(p)switch(e){case 3:return!0;case 5:return h;case 6:return g;case 2:Na(S,h)}else switch(e){case 4:return!1;case 7:Na(S,h)}return s?-1:n||r?r:S}},Pa={forEach:Da(0),map:Da(1),filter:Da(2),some:Da(3),every:Da(4),find:Da(5),findIndex:Da(6),filterReject:Da(7)},La=wi,ka=h,Ma=L,Ua=d,xa=N,Va=Te,Fa=n,Ba=Ze,ja=l,Ga=ii,Wa=Z,Ha=Ct,Ka=pn,Ya=B,qa=go,za=Ys,Ja=To,Xa=Co,Qa=ko,Za=O,$a=Qt,ec=Ms,tc=k,ic=Uo,nc=Vo,rc=Ye,sc=Us,oc=nt,ac=ht,cc=Fo,dc=zo,lc=$o,uc=ca,hc=va,pc=Pa.forEach,_c=no(\"hidden\"),Ec=\"Symbol\",mc=\"prototype\",fc=hc.set,gc=hc.getterFor(Ec),Tc=Object[mc],Sc=ka.Symbol,Rc=Sc&&Sc[mc],Cc=ka.TypeError,Ic=ka.QObject,vc=Za.f,yc=$a.f,Ac=Xa.f,bc=tc.f,wc=Ua([].push),Oc=rc(\"symbols\"),Nc=rc(\"op-symbols\"),Dc=rc(\"wks\"),Pc=!Ic||!Ic[mc]||!Ic[mc].findChild,Lc=xa&&Fa((function(){return 7!=qa(yc({},\"a\",{get:function(){return yc(this,\"a\",{value:7}).a}})).a}))?function(e,t,i){var n=vc(Tc,t);n&&delete Tc[t],yc(e,t,i),n&&e!==Tc&&yc(Tc,t,n)}:yc,kc=function(e,t){var i=Oc[e]=qa(Rc);return fc(i,{type:Ec,tag:e,description:t}),xa||(i.description=t),i},Mc=function(e,t,i){e===Tc&&Mc(Nc,t,i),Ga(e);var n=Ha(t);return Ga(i),Ba(Oc,n)?(i.enumerable?(Ba(e,_c)&&e[_c][n]&&(e[_c][n]=!1),i=qa(i,{enumerable:Ya(0,!1)})):(Ba(e,_c)||yc(e,_c,Ya(1,{})),e[_c][n]=!0),Lc(e,n,i)):yc(e,n,i)},Uc=function(e,t){Ga(e);var i=Wa(t),n=za(i).concat(Bc(i));return pc(n,(function(t){xa&&!Ma(xc,i,t)||Mc(e,t,i[t])})),e},xc=function(e){var t=Ha(e),i=Ma(bc,this,t);return!(this===Tc&&Ba(Oc,t)&&!Ba(Nc,t))&&(!(i||!Ba(this,t)||!Ba(Oc,t)||Ba(this,_c)&&this[_c][t])||i)},Vc=function(e,t){var i=Wa(e),n=Ha(t);if(i!==Tc||!Ba(Oc,n)||Ba(Nc,n)){var r=vc(i,n);return!r||!Ba(Oc,n)||Ba(i,_c)&&i[_c][n]||(r.enumerable=!0),r}},Fc=function(e){var t=Ac(Wa(e)),i=[];return pc(t,(function(e){Ba(Oc,e)||Ba(sc,e)||wc(i,e)})),i},Bc=function(e){var t=e===Tc,i=Ac(t?Nc:Wa(e)),n=[];return pc(i,(function(e){!Ba(Oc,e)||t&&!Ba(Tc,e)||wc(n,Oc[e])})),n};Va||(Sc=function(){if(ja(Rc,this))throw Cc(\"Symbol is not a constructor\");var e=arguments.length&&void 0!==arguments[0]?Ka(arguments[0]):void 0,t=oc(e),i=function(e){this===Tc&&Ma(i,Nc,e),Ba(this,_c)&&Ba(this[_c],t)&&(this[_c][t]=!1),Lc(this,t,Ya(1,e))};return xa&&Pc&&Lc(Tc,t,{configurable:!0,set:i}),kc(t,e)},ic(Rc=Sc[mc],\"toString\",(function(){return gc(this).tag})),ic(Sc,\"withoutSetter\",(function(e){return kc(oc(e),e)})),tc.f=xc,$a.f=Mc,ec.f=Uc,Za.f=Vc,Ja.f=Xa.f=Fc,Qa.f=Bc,cc.f=function(e){return kc(ac(e),e)},xa&&nc(Rc,\"description\",{configurable:!0,get:function(){return gc(this).description}})),La({global:!0,constructor:!0,wrap:!0,forced:!Va,sham:!Va},{Symbol:Sc}),pc(za(Dc),(function(e){dc(e)})),La({target:Ec,stat:!0,forced:!Va},{useSetter:function(){Pc=!0},useSimple:function(){Pc=!1}}),La({target:\"Object\",stat:!0,forced:!Va,sham:!xa},{create:function(e,t){return void 0===t?qa(e):Uc(qa(e),t)},defineProperty:Mc,defineProperties:Uc,getOwnPropertyDescriptor:Vc}),La({target:\"Object\",stat:!0,forced:!Va},{getOwnPropertyNames:Fc}),lc(),uc(Sc,Ec),sc[_c]=!0;var jc=Te&&!!Symbol.for&&!!Symbol.keyFor,Gc=wi,Wc=ae,Hc=Ze,Kc=pn,Yc=Ye,qc=jc,zc=Yc(\"string-to-symbol-registry\"),Jc=Yc(\"symbol-to-string-registry\");Gc({target:\"Symbol\",stat:!0,forced:!qc},{for:function(e){var t=Kc(e);if(Hc(zc,t))return zc[t];var i=Wc(\"Symbol\")(t);return zc[t]=i,Jc[i]=t,i}});var Xc=wi,Qc=Ze,Zc=ye,$c=be,ed=jc,td=Ye(\"symbol-to-string-registry\");Xc({target:\"Symbol\",stat:!0,forced:!ed},{keyFor:function(e){if(!Zc(e))throw TypeError($c(e)+\" is not a symbol\");if(Qc(td,e))return td[e]}});var id=d([].slice),nd=jr,rd=w,sd=R,od=pn,ad=d([].push),cd=wi,dd=ae,ld=f,ud=L,hd=d,pd=n,_d=w,Ed=ye,md=id,fd=function(e){if(rd(e))return e;if(nd(e)){for(var t=e.length,i=[],n=0;n=t.length?(e.target=void 0,Zl(void 0,!0)):Zl(\"keys\"==i?n:\"values\"==i?t[n]:[n,t[n]],!1)}),\"values\"),Jl.Arguments=Jl.Array;var iu={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0},nu=h,ru=ln,su=mi,ou=Gd,au=ht(\"toStringTag\");for(var cu in iu){var du=nu[cu],lu=du&&du.prototype;lu&&ru(lu)!==au&&su(lu,au,cu),ou[cu]=ou.Array}var uu=jd,hu=ht,pu=Qt.f,_u=hu(\"metadata\"),Eu=Function.prototype;void 0===Eu[_u]&&pu(Eu,_u,{value:null}),zo(\"dispose\"),zo(\"metadata\");var mu=uu;zo(\"asyncDispose\");var fu=d,gu=ae(\"Symbol\"),Tu=gu.keyFor,Su=fu(gu.prototype.valueOf),Ru=gu.isRegisteredSymbol||function(e){try{return void 0!==Tu(Su(e))}catch(e){return!1}};wi({target:\"Symbol\",stat:!0},{isRegisteredSymbol:Ru});for(var Cu=Ye,Iu=ae,vu=d,yu=ye,Au=ht,bu=Iu(\"Symbol\"),wu=bu.isWellKnownSymbol,Ou=Iu(\"Object\",\"getOwnPropertyNames\"),Nu=vu(bu.prototype.valueOf),Du=Cu(\"wks\"),Pu=0,Lu=Ou(bu),ku=Lu.length;Pu=a?e?\"\":void 0:(n=Wu(s,o))<55296||n>56319||o+1===a||(r=Wu(s,o+1))<56320||r>57343?e?Gu(s,o):n:e?Hu(s,o,o+2):r-56320+(n-55296<<10)+65536}},Yu={codeAt:Ku(!1),charAt:Ku(!0)},qu=Yu.charAt,zu=pn,Ju=va,Xu=Yl,Qu=ql,Zu=\"String Iterator\",$u=Ju.set,eh=Ju.getterFor(Zu);Xu(String,\"String\",(function(e){$u(this,{type:Zu,string:zu(e),index:0})}),(function(){var e,t=eh(this),i=t.string,n=t.index;return n>=i.length?Qu(void 0,!0):(e=qu(i,n),t.index+=e.length,Qu(e,!1))}));var th=i(Fo.f(\"iterator\"));function ih(e){return ih=\"function\"==typeof xu&&\"symbol\"==typeof th?function(e){return typeof e}:function(e){return e&&\"function\"==typeof xu&&e.constructor===xu&&e!==xu.prototype?\"symbol\":typeof e},ih(e)}var nh=i(Fo.f(\"toPrimitive\"));function rh(e){var t=function(e,t){if(\"object\"!==ih(e)||null===e)return e;var i=e[nh];if(void 0!==i){var n=i.call(e,t||\"default\");if(\"object\"!==ih(n))return n;throw new TypeError(\"@@toPrimitive must return a primitive value.\")}return(\"string\"===t?String:Number)(e)}(e,\"string\");return\"symbol\"===ih(t)?t:String(t)}function sh(e,t,i){return(t=rh(t))in e?Fr(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}var oh=zi(\"Array\").keys,ah=ln,ch=Ze,dh=l,lh=oh,uh=Array.prototype,hh={DOMTokenList:!0,NodeList:!0},ph=i((function(e){var t=e.keys;return e===uh||dh(uh,e)&&t===uh.keys||ch(hh,ah(e))?lh:t})),_h=be,Eh=TypeError,mh=wo,fh=Math.floor,gh=function(e,t){var i=e.length,n=fh(i/2);return i<8?Th(e,t):Sh(e,gh(mh(e,0,n),t),gh(mh(e,n),t),t)},Th=function(e,t){for(var i,n,r=e.length,s=1;s0;)e[n]=e[--n];n!==s++&&(e[n]=i)}return e},Sh=function(e,t,i,n){for(var r=t.length,s=i.length,o=0,a=0;o3)){if(Bh)return!0;if(Gh)return Gh<603;var e,t,i,n,r=\"\";for(e=65;e<76;e++){switch(t=String.fromCharCode(e),e){case 66:case 69:case 70:case 72:i=3;break;case 68:case 71:i=4;break;default:i=2}for(n=0;n<47;n++)Wh.push({k:t+n,v:i})}for(Wh.sort((function(e,t){return t.v-e.v})),n=0;nMh(i)?1:-1}}(e)),i=Lh(r),n=0;ns;s++)if((a=f(e[s]))&&Qp(n_,a))return a;return new i_(!1)}n=Zp(e,r)}for(c=h?e.next:n.next;!(d=Yp(c,n)).done;){try{a=f(d.value)}catch(e){e_(n,\"throw\",e)}if(\"object\"==typeof a&&a&&Qp(n_,a))return a}return new i_(!1)},s_=pn,o_=wi,a_=l,c_=nl,d_=Ol,l_=function(e,t,i){for(var n=cp(t),r=lp.f,s=dp.f,o=0;o2&&__(i,arguments[2]);var r=[];return m_(e,S_,{that:r}),h_(i,\"errors\",r),i};d_?d_(R_,T_):l_(R_,T_,{name:!0});var C_=R_.prototype=u_(T_.prototype,{constructor:p_(1,R_),message:p_(1,\"\"),name:p_(1,\"AggregateError\")});o_({global:!0,constructor:!0,arity:2},{AggregateError:R_});var I_,v_,y_,A_,b_=\"undefined\"!=typeof process&&\"process\"==R(process),w_=ae,O_=Vo,N_=N,D_=ht(\"species\"),P_=l,L_=TypeError,k_=function(e,t){if(P_(t,e))return e;throw L_(\"Incorrect invocation\")},M_=ls,U_=be,x_=TypeError,V_=ii,F_=function(e){if(M_(e))return e;throw x_(U_(e)+\" is not a constructor\")},B_=Y,j_=ht(\"species\"),G_=function(e,t){var i,n=V_(e).constructor;return void 0===n||B_(i=V_(n)[j_])?t:F_(i)},W_=TypeError,H_=function(e,t){if(e{};function lg(){const e={promise:void 0,isResolved:!1,isRejected:!1,isFinished:!1,resolve:void 0,reject:void 0,cancel:dg};return e.promise=new cg(((t,i)=>{e.resolve=i=>{e.isFinished||(e.isResolved=!0,e.isFinished=!0,t(i),e.value=i)},e.reject=t=>{e.isFinished||(e.isRejected=!0,e.isFinished=!0,i(t))}})),e}const ug=new Map,hg=new Map,pg=new Map;var _g,Eg;!function(e){e.WIN_10=\"Windows 10\",e.WIN_81=\"Windows 8.1\",e.WIN_8=\"Windows 8\",e.WIN_7=\"Windows 7\",e.WIN_VISTA=\"Windows Vista\",e.WIN_SERVER_2003=\"Windows Server 2003\",e.WIN_XP=\"Windows XP\",e.WIN_2000=\"Windows 2000\",e.ANDROID=\"Android\",e.HARMONY_OS=\"HarmonyOS\",e.OPEN_BSD=\"Open BSD\",e.SUN_OS=\"Sun OS\",e.LINUX=\"Linux\",e.IOS=\"iOS\",e.MAC_OS=\"Mac OS\",e.CHROMIUM_OS=\"Chromium OS\",e.QNX=\"QNX\",e.UNIX=\"UNIX\",e.BEOS=\"BeOS\",e.OS_2=\"OS/2\",e.SEARCH_BOT=\"Search Bot\"}(_g||(_g={})),function(e){e.CHROME=\"Chrome\",e.SAFARI=\"Safari\",e.EDGE=\"Edge\",e.FIREFOX=\"Firefox\",e.OPERA=\"OPR\",e.QQ=\"QQBrowser\",e.WECHAT=\"MicroMessenger\"}(Eg||(Eg={}));var mg={exports:{}};!function(e,i){!function(t,n){var r=\"function\",s=\"undefined\",o=\"object\",a=\"string\",c=\"major\",d=\"model\",l=\"name\",u=\"type\",h=\"vendor\",p=\"version\",_=\"architecture\",E=\"console\",m=\"mobile\",f=\"tablet\",g=\"smarttv\",T=\"wearable\",S=\"embedded\",R=\"Amazon\",C=\"Apple\",I=\"ASUS\",v=\"BlackBerry\",y=\"Browser\",A=\"Chrome\",b=\"Firefox\",w=\"Google\",O=\"Huawei\",N=\"LG\",D=\"Microsoft\",P=\"Motorola\",L=\"Opera\",k=\"Samsung\",M=\"Sharp\",U=\"Sony\",x=\"Xiaomi\",V=\"Zebra\",F=\"Facebook\",B=\"Chromium OS\",j=\"Mac OS\",G=function(e){for(var t={},i=0;i0?2===c.length?typeof c[1]==r?this[c[0]]=c[1].call(this,l):this[c[0]]=c[1]:3===c.length?typeof c[1]!==r||c[1].exec&&c[1].test?this[c[0]]=l?l.replace(c[1],c[2]):n:this[c[0]]=l?c[1].call(this,l,c[2]):n:4===c.length&&(this[c[0]]=l?c[3].call(this,l.replace(c[1],c[2])):n):this[c]=l||n;u+=2}},q=function(e,t){for(var i in t)if(typeof t[i]===o&&t[i].length>0){for(var r=0;r2&&(e[d]=\"iPad\",e[u]=f),e},this.getEngine=function(){var e={};return e[l]=n,e[p]=n,Y.call(e,g,S.engine),e},this.getOS=function(){var e={};return e[l]=n,e[p]=n,Y.call(e,g,S.os),!e[l]&&T&&\"Unknown\"!=T.platform&&(e[l]=T.platform.replace(/chrome os/i,B).replace(/macos/i,j)),e},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return g},this.setUA=function(e){return g=typeof e===a&&e.length>350?K(e,350):e,this},this.setUA(g),this};X.VERSION=\"0.7.34\",X.BROWSER=G([l,p,c]),X.CPU=G([_]),X.DEVICE=G([d,h,u,E,m,g,f,T,S]),X.ENGINE=X.OS=G([l,p]),e.exports&&(i=e.exports=X),i.UAParser=X;var Q=typeof t!==s&&(t.jQuery||t.Zepto);if(Q&&!Q.ua){var Z=new X;Q.ua=Z.getResult(),Q.ua.get=function(){return Z.getUA()},Q.ua.set=function(e){Z.setUA(e);var t=Z.getResult();for(var i in t)Q.ua[i]=t[i]}}}(\"object\"==typeof window?window:t)}(mg,mg.exports);const fg=new(i(mg.exports));let gg=fg.getResult(),Tg=null;function Sg(e){if(!Tg){e&&fg.setUA(e),gg=fg.getResult();const t=function(e){if(\"Blink\"===e.engine.name&&\"WeChat\"!==e.browser.name)return Eg.CHROME;switch(e.browser.name){case\"Chrome Headless\":case\"Chrome\":case\"Chromium\":return Eg.CHROME;case\"Safari\":case\"Mobile Safari\":return Eg.SAFARI;case\"Edge\":return Eg.EDGE;case\"Firefox\":return Eg.FIREFOX;case\"QQBrowser\":return Eg.QQ;case\"Opera\":return Eg.OPERA;case\"WeChat\":return Eg.WECHAT;default:return e.browser.name||\"\"}}(gg),i=function(e){let t;t=\"Blink\"===e.engine.name?e.engine.version||\"\":e.browser.version||\"\";return t.split(\".\")[0]}(gg),n=function(e){if(\"Windows\"===e.os.name)return e.os.version?e.os.name+\" \"+e.os.version:e.os.name;return e.os.name||\"\"}(gg),r=gg.os.version;if(!(t&&i&&n&&r))return{name:t,version:i,os:n,osVersion:r};Tg={name:t,version:i,os:n,osVersion:r}}return Tg}function Rg(){return Sg().os}function Cg(){const e=Sg();return\"\".concat(e.os,\" \").concat(e.osVersion)}function Ig(){const e=Sg();return!!(\"WebKit\"===gg.engine.name&&e.os===_g.MAC_OS&&navigator.maxTouchPoints&&navigator.maxTouchPoints>0&&e.name!==Eg.SAFARI||Og()&&e.name!==Eg.SAFARI)}function vg(){const e=Sg();if(Ig()){if(e.os===_g.MAC_OS)return!0;if(e.os===_g.IOS){const e=gg.os.version&&gg.os.version.split(\".\");if(e&&14===Number(e[0])&&e[1]&&Number(e[1])>=3)return!0;if(e&&Number(e[0])>14)return!0}}return!1}function yg(){return\"WebKit\"===gg.engine.name}function Ag(){return Sg().name===Eg.CHROME}function bg(){return Sg().name===Eg.SAFARI}function wg(){return Sg().name===Eg.FIREFOX}function Og(){return Sg().os===_g.IOS}function Ng(e){const t=Sg();return!(t.name!==Eg.CHROME||!t.osVersion)&&Number(t.version)>=e}function Dg(e){const t=Sg();return!(t.name!==Eg.EDGE||!t.osVersion)&&Number(t.version)>=e}function Pg(e){const t=Sg();return!(t.name!==Eg.OPERA||!t.osVersion)&&Number(t.version)>=e}function Lg(){const e=Sg();return!(e.name!==Eg.CHROME||!e.osVersion)&&Number(e.version)<=90}function kg(){const e=Sg();if(e.os!==_g.IOS||!e.osVersion)return!1;const t=e.osVersion.split(\".\");return Number(t[0])<14||14===Number(t[0])&&Number(t[1])<=6}function Mg(){const e=Sg();if(e.os!==_g.IOS||!e.osVersion)return!1;const t=e.osVersion.split(\".\");return 15===Number(t[0])}function Ug(){const e=Sg();if(e.os!==_g.IOS||!e.osVersion)return!1;const t=e.osVersion.split(\".\");return 16===Number(t[0])}function xg(){const e=Sg();if(e.os!==_g.IOS||!e.osVersion)return!1;const t=e.osVersion.split(\".\");return 15===Number(t[0])&&Number(t[1])>=1}function Vg(){return bg()&&navigator.maxTouchPoints>0}function Fg(){return Sg().name===Eg.WECHAT}function Bg(){return window.navigator.appVersion&&null!==window.navigator.appVersion.match(/Chrome\\/([\\w\\W]*?)\\./)&&window.navigator.appVersion.match(/Chrome\\/([\\w\\W]*?)\\./)[1]<=35}function jg(){const e=Sg();if(e.name===Eg.EDGE||e.name===Eg.SAFARI)return!1;return!!navigator.userAgent.toLocaleLowerCase().match(/chrome\\/[\\d]./i)}function Gg(){return Rg()===_g.ANDROID}function Wg(){const e=Sg();return Gg()&&(e.name===Eg.CHROME||e.name===Eg.WECHAT||/chrome|chromium/i.test(navigator.userAgent))}var Hg;!function(e){e.UNEXPECTED_ERROR=\"UNEXPECTED_ERROR\",e.UNEXPECTED_RESPONSE=\"UNEXPECTED_RESPONSE\",e.TIMEOUT=\"TIMEOUT\",e.INVALID_PARAMS=\"INVALID_PARAMS\",e.NOT_READABLE=\"NOT_READABLE\",e.NOT_SUPPORTED=\"NOT_SUPPORTED\",e.INVALID_OPERATION=\"INVALID_OPERATION\",e.OPERATION_ABORTED=\"OPERATION_ABORTED\",e.WEB_SECURITY_RESTRICT=\"WEB_SECURITY_RESTRICT\",e.EXCHANGE_SDP_FAILED=\"EXCHANGE_SDP_FAILED\",e.ADD_CANDIDATE_FAILED=\"ADD_CANDIDATE_FAILED\",e.DATACHANNEL_FAILED=\"DATACHANNEL_FAILED\",e.NETWORK_ERROR=\"NETWORK_ERROR\",e.NETWORK_TIMEOUT=\"NETWORK_TIMEOUT\",e.NETWORK_RESPONSE_ERROR=\"NETWORK_RESPONSE_ERROR\",e.API_INVOKE_TIMEOUT=\"API_INVOKE_TIMEOUT\",e.ENUMERATE_DEVICES_FAILED=\"ENUMERATE_DEVICES_FAILED\",e.DEVICE_NOT_FOUND=\"DEVICE_NOT_FOUND\",e.ELECTRON_IS_NULL=\"ELECTRON_IS_NULL\",e.ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR=\"ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR\",e.CHROME_PLUGIN_NO_RESPONSE=\"CHROME_PLUGIN_NO_RESPONSE\",e.CHROME_PLUGIN_NOT_INSTALL=\"CHROME_PLUGIN_NOT_INSTALL\",e.MEDIA_OPTION_INVALID=\"MEDIA_OPTION_INVALID\",e.PERMISSION_DENIED=\"PERMISSION_DENIED\",e.CONSTRAINT_NOT_SATISFIED=\"CONSTRAINT_NOT_SATISFIED\",e.TRACK_IS_DISABLED=\"TRACK_IS_DISABLED\",e.GET_VIDEO_ELEMENT_VISIBLE_ERROR=\"GET_VIDEO_ELEMENT_VISIBLE_ERROR\",e.SHARE_AUDIO_NOT_ALLOWED=\"SHARE_AUDIO_NOT_ALLOWED\",e.LOW_STREAM_ENCODING_ERROR=\"LOW_STREAM_ENCODING_ERROR\",e.SET_ENCODING_PARAMETER_ERROR=\"SET_ENCODING_PARAMETER_ERROR\",e.TRACK_STATE_UNREACHABLE=\"TRACK_STATE_UNREACHABLE\",e.INVALID_UINT_UID_FROM_STRING_UID=\"INVALID_UINT_UID_FROM_STRING_UID\",e.CAN_NOT_GET_PROXY_SERVER=\"CAN_NOT_GET_PROXY_SERVER\",e.CAN_NOT_GET_GATEWAY_SERVER=\"CAN_NOT_GET_GATEWAY_SERVER\",e.VOID_GATEWAY_ADDRESS=\"VOID_GATEWAY_ADDRESS\",e.UID_CONFLICT=\"UID_CONFLICT\",e.MULTI_UNILBS_RESPONSE_ERROR=\"MULTI_UNILBS_RESPONSE_ERROR\",e.UPDATE_TICKET_FAILED=\"UPDATE_TICKET_FAILED\",e.INVALID_LOCAL_TRACK=\"INVALID_LOCAL_TRACK\",e.INVALID_TRACK=\"INVALID_TRACK\",e.SENDER_NOT_FOUND=\"SENDER_NOT_FOUND\",e.CREATE_OFFER_FAILED=\"CREATE_OFFER_FAILED\",e.SET_ANSWER_FAILED=\"SET_ANSWER_FAILED\",e.ICE_FAILED=\"ICE_FAILED\",e.PC_CLOSED=\"PC_CLOSED\",e.SENDER_REPLACE_FAILED=\"SENDER_REPLACE_FAILED\",e.GET_LOCAL_CAPABILITIES_FAILED=\"GET_LOCAL_CAPABILITIES_FAILED\",e.GET_LOCAL_CONNECTION_PARAMS_FAILED=\"GET_LOCAL_CONNECTION_PARAMS_FAILED\",e.SUBSCRIBE_FAILED=\"SUBSCRIBE_FAILED\",e.UNSUBSCRIBE_FAILED=\"UNSUBSCRIBE_FAILED\",e.GATEWAY_P2P_LOST=\"GATEWAY_P2P_LOST\",e.NO_ICE_CANDIDATE=\"NO_ICE_CANDIDATE\",e.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS=\"CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS\",e.EXIST_DISABLED_VIDEO_TRACK=\"EXIST_DISABLED_VIDEO_TRACK\",e.INVALID_REMOTE_USER=\"INVALID_REMOTE_USER\",e.REMOTE_USER_IS_NOT_PUBLISHED=\"REMOTE_USER_IS_NOT_PUBLISHED\",e.CUSTOM_REPORT_SEND_FAILED=\"CUSTOM_REPORT_SEND_FAILED\",e.CUSTOM_REPORT_FREQUENCY_TOO_HIGH=\"CUSTOM_REPORT_FREQUENCY_TOO_HIGH\",e.FETCH_AUDIO_FILE_FAILED=\"FETCH_AUDIO_FILE_FAILED\",e.READ_LOCAL_AUDIO_FILE_ERROR=\"READ_LOCAL_AUDIO_FILE_ERROR\",e.DECODE_AUDIO_FILE_FAILED=\"DECODE_AUDIO_FILE_FAILED\",e.WS_ABORT=\"WS_ABORT\",e.WS_DISCONNECT=\"WS_DISCONNECT\",e.WS_ERR=\"WS_ERR\",e.EXTERNAL_SIGNAL_ABORT=\"EXTERNAL_SIGNAL_ABORT\",e.LIVE_STREAMING_TASK_CONFLICT=\"LIVE_STREAMING_TASK_CONFLICT\",e.LIVE_STREAMING_INVALID_ARGUMENT=\"LIVE_STREAMING_INVALID_ARGUMENT\",e.LIVE_STREAMING_INTERNAL_SERVER_ERROR=\"LIVE_STREAMING_INTERNAL_SERVER_ERROR\",e.LIVE_STREAMING_PUBLISH_STREAM_NOT_AUTHORIZED=\"LIVE_STREAMING_PUBLISH_STREAM_NOT_AUTHORIZED\",e.LIVE_STREAMING_TRANSCODING_NOT_SUPPORTED=\"LIVE_STREAMING_TRANSCODING_NOT_SUPPORTED\",e.LIVE_STREAMING_CDN_ERROR=\"LIVE_STREAMING_CDN_ERROR\",e.LIVE_STREAMING_INVALID_RAW_STREAM=\"LIVE_STREAMING_INVALID_RAW_STREAM\",e.LIVE_STREAMING_WARN_STREAM_NUM_REACH_LIMIT=\"LIVE_STREAMING_WARN_STREAM_NUM_REACH_LIMIT\",e.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE=\"LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE\",e.LIVE_STREAMING_WARN_FREQUENT_REQUEST=\"LIVE_STREAMING_WARN_FREQUENT_REQUEST\",e.WEBGL_INTERNAL_ERROR=\"WEBGL_INTERNAL_ERROR\",e.BEAUTY_PROCESSOR_INTERNAL_ERROR=\"BEAUTY_PROCESSOR_INTERNAL_ERROR\",e.CROSS_CHANNEL_WAIT_STATUS_ERROR=\"CROSS_CHANNEL_WAIT_STATUS_ERROR\",e.CROSS_CHANNEL_FAILED_JOIN_SRC=\"CROSS_CHANNEL_FAILED_JOIN_SEC\",e.CROSS_CHANNEL_FAILED_JOIN_DEST=\"CROSS_CHANNEL_FAILED_JOIN_DEST\",e.CROSS_CHANNEL_FAILED_PACKET_SENT_TO_DEST=\"CROSS_CHANNEL_FAILED_PACKET_SENT_TO_DEST\",e.CROSS_CHANNEL_SERVER_ERROR_RESPONSE=\"CROSS_CHANNEL_SERVER_ERROR_RESPONSE\",e.METADATA_OUT_OF_RANGE=\"METADATA_OUT_OF_RANGE\",e.LOCAL_AEC_ERROR=\"LOCAL_AEC_ERROR\",e.INVALID_PLUGIN=\"INVALID_PLUGIN\",e.DISCONNECT_P2P=\"DISCONNECT_P2P\",e.INIT_WEBSOCKET_TIMEOUT=\"INIT_WEBSOCKET_TIMEOUT\",e.CONVERTING_IMAGEDATA_TO_BLOB_FAILED=\"CONVERTING_IMAGEDATA_TO_BLOB_FAILED\",e.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED=\"CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED\",e.INIT_DATACHANNEL_TIMEOUT=\"INIT_DATACHANNEL_TIMEOUT\",e.CREATE_DATACHANNEL_ERROR=\"CREATE_DATACHANNEL_ERROR\",e.DATACHANNEL_CONNECTION_TIMEOUT=\"DATACHANNEL_CONNECTION_TIMEOUT\",e.PROHIBITED_OPERATION=\"PROHIBITED_OPERATION\",e.IMAGE_MODERATION_UPLOAD_FAILED=\"IMAGE_MODERATION_UPLOAD_FAILED\",e.P2P_MESSAGE_FAILED=\"P2P_MESSAGE_FAILED\"}(Hg||(Hg={}));let Kg=class extends Error{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:\"\",i=arguments.length>2?arguments[2]:void 0;super(t),sh(this,\"code\",void 0),sh(this,\"message\",void 0),sh(this,\"data\",void 0),sh(this,\"name\",\"AgoraRTCException\"),this.code=e,this.message=\"AgoraRTCError \".concat(this.code,\": \").concat(t),this.data=i}toString(){return this.data?\"data: \".concat(JSON.stringify(this.data),\"\\n\").concat(this.stack):\"\".concat(this.stack)}print(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:\"error\",t=arguments.length>1?arguments[1]:void 0;return\"error\"===e&&(t||console).error(this.toString()),\"warning\"===e&&(t||console).warn(this.toString()),this}throw(e){throw this.print(\"error\",e),this}};function Yg(e,t){if(\"boolean\"!=typeof e)throw new Kg(Hg.INVALID_PARAMS,\"Invalid \".concat(t,\": The value is of the boolean type.\"))}function qg(e,t,i){if(bn(i).call(i,e))return;throw new Kg(Hg.INVALID_PARAMS,\"\".concat(t,\" can only be set as \").concat(JSON.stringify(i)))}function zg(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1e4;if(en||(!(arguments.length>4&&void 0!==arguments[4])||arguments[4])&&!function(e){return\"number\"==typeof e&&e%1==0}(e)){throw new Kg(Hg.INVALID_PARAMS,\"invalid \".concat(t,\": the value range is [\").concat(i,\", \").concat(n,\"]. integer only\"))}}function Jg(e,t){if(\"number\"!=typeof e){if(!(e.min||e.max||e.ideal||e.exact)){throw new Kg(Hg.INVALID_PARAMS,\"\".concat(t,\" is not a valid ConstrainLong\"))}void 0!==e.min&&zg(e.min,\"\".concat(t,\".min\"),0,1/0),void 0!==e.max&&zg(e.max,\"\".concat(t,\".max\"),1,1/0),void 0!==e.exact&&zg(e.exact,\"\".concat(t,\".exact\"),1,1/0),void 0!==e.ideal&&zg(e.ideal,\"\".concat(t,\".ideal\"),1,1/0)}else zg(e,t,1,1/0)}function Xg(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:255,r=!(arguments.length>4&&void 0!==arguments[4])||arguments[4];if(null==e)throw new Kg(Hg.INVALID_PARAMS,\"\".concat(t||\"param\",\" cannot be empty\"));if(!$g(e,i,n,r))throw new Kg(Hg.INVALID_PARAMS,\"Invalid \".concat(t||\"string param\",\": Length of the string: [\").concat(i,\",\").concat(n,\"].\").concat(r?\" ASCII characters only.\":\"\"))}function Qg(e,t){if(!Array.isArray(e))throw new Kg(Hg.INVALID_PARAMS,\"\".concat(t,\" should be an array\"))}function Zg(e){return null==e}function $g(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:255,n=!(arguments.length>3&&void 0!==arguments[3])||arguments[3];return\"string\"==typeof e&&e.length<=i&&e.length>=t&&(!n||function(e){if(\"string\"!=typeof e)return!1;for(let t=0;t255)return!1}return!0}(e))}function eT(e,t,i){if(\"getBigUint64\"in DataView.prototype)return e.getBigUint64(t,i);const n=e.getUint32(t,i),r=e.getUint32(t+4,i),s=Number(!!i),o=Number(!i);return BigInt(n*o+r*s)<>BigInt(32)),s=Number(i&BigInt(4294967295));n?(e.setUint32(t+4,r,n),e.setUint32(t,s,n)):(e.setUint32(t,r,n),e.setUint32(t+4,s,n))}var iT,nT;!function(e){e.COVERED=\"COVERED\",e.POSITION=\"POSITION\",e.SIZE=\"SIZE\",e.STYLE=\"STYLE\"}(iT||(iT={})),function(e){e.UNMOUNTED=\"UNMOUNTED\",e.INVALID_HTML_ELEMENT=\"INVALID_HTML_ELEMENT\"}(nT||(nT={}));const rT=new class{constructor(){sh(this,\"_clientSize\",null),sh(this,\"getClientWidth\",(()=>document.documentElement?document.documentElement.clientWidth:document.body.clientWidth)),sh(this,\"getClientHeight\",(()=>document.documentElement?document.documentElement.clientHeight:document.body.clientHeight)),sh(this,\"getStyle\",(e=>window.getComputedStyle(e,null))),sh(this,\"checkCssVisibleProperty\",(e=>{var t;let i=!0;const n=this.getStyle(e),{display:r,visibility:s,opacity:o,filter:a}=n;if((\"none\"===r||bn(t=[\"hidden\",\"collapse\"]).call(t,s)||Number(o)<.1)&&(i=!1),!i)return!1;if(a){a.split(\" \").filter((e=>{var t;const i=e.split(\"(\")[0];return bn(t=[\"brightness\",\"blur\",\"opacity\"]).call(t,i)})).map((e=>{const[t,i]=e.split(/\\(|\\)/);return[t,Number(i.match(/^[0-9\\.]+/))]})).forEach((e=>{const[t,n]=e;switch(t){case\"brightness\":(n<.1||n>3)&&(i=!1);break;case\"blur\":n>3&&(i=!1);break;case\"opacity\":n<.1&&(i=!1)}}))}return i})),sh(this,\"checkPropertyUpToAllParentNodes\",((e,t)=>{let i=!0,n=!0;const r=e=>t(e);let s=e;for(;s&&n;){r(s)||(i=!1,n=!1),s=s.parentElement,s||(n=!1)}return i})),sh(this,\"checkActualCssVisibleIncludeInherit\",(e=>this.checkPropertyUpToAllParentNodes(e,this.checkCssVisibleProperty))),sh(this,\"getSizeAboutClient\",(e=>{const{width:t,height:i,left:n,right:r,top:s,bottom:o}=e.getBoundingClientRect(),a=this.getClientWidth(),c=this.getClientHeight();return{width:t,height:i,left:n,right:r,top:s,bottom:o,clientWidth:a,clientHeight:c,clientMin:Math.min(a,c)}})),sh(this,\"checkActualSize\",(()=>{const{width:e,height:t,clientMin:i}=this._clientSize;return this.checkSizeIsVisible(e,t,i)})),sh(this,\"elementFromPoint\",((e,t)=>document.elementFromPoint?document.elementFromPoint(e,t):null)),sh(this,\"checkCoverForAPoint\",((e,t,i)=>{const n=this.elementFromPoint(e,t);return null!==n&&n!==i})),sh(this,\"getPointPositionList\",(()=>{const{width:e,height:t,left:i,top:n}=this._clientSize,r=e/6,s=t/6,o=[],a=10**6;for(let e=0;e<5;e++)for(let t=0;t<5;t++){const c=(i*a+(0===e?.1:4===e?(r*e*a-1e5)/a:r*e)*a)/a,d=(n*a+(0===t?.1:4===t?(s*t*a-1e5)/a:s*t)*a)/a;o.push({x:c,y:d})}return[...o]})),sh(this,\"checkElementCover\",(e=>this.getPointPositionList().map((t=>this.checkCoverForAPoint(t.x,t.y,e))).filter((e=>!!e)).length>6)),sh(this,\"checkSizeIsVisible\",((e,t,i)=>(e>50||i/e<=10)&&(t>50||i/t<=10))),sh(this,\"checkSizeOfPartInClient\",(()=>{const{left:e,right:t,top:i,bottom:n,clientHeight:r,clientWidth:s,clientMin:o}=this._clientSize;let a,c,d,l;if(e<0)a=0;else{if(!(e(this._clientSize=null,{visible:!1,reason:e}))),sh(this,\"checkOneElementVisible\",(e=>{if(e instanceof HTMLElement){if(this.checkElementIsMountedOnDom(e)){if(this.checkActualCssVisibleIncludeInherit(e)){if(this._clientSize=this.getSizeAboutClient(e),this.checkElementCover(e))return this.returnHiddenResult(iT.COVERED);{const e=this.checkActualSize(),t=this.checkSizeOfPartInClient();return e&&!t?this.returnHiddenResult(iT.POSITION):e?(this._clientSize=null,{visible:!0}):this.returnHiddenResult(iT.SIZE)}}return this.returnHiddenResult(iT.STYLE)}return this.returnHiddenResult(nT.UNMOUNTED)}return this.returnHiddenResult(nT.INVALID_HTML_ELEMENT)})),sh(this,\"checkElementIsMountedOnDom\",(e=>this.checkPropertyUpToAllParentNodes(e,(e=>\"HTML\"!==e.nodeName.toUpperCase()?null!==e.parentElement:!!document.documentElement))))}};function sT(e){return(new TextEncoder).encode(e)}const oT=function(e,t){const i=new Uint8Array(e.byteLength+t.byteLength);return i.set(new Uint8Array(e),0),i.set(new Uint8Array(t),e.byteLength),i};const aT=async e=>{const t=function(e){const t=window.atob(e),i=new Uint8Array(new ArrayBuffer(t.length));for(let e=0;efunction(e,t){let i=\"\";return new Uint8Array(e).forEach((e=>{i+=e.toString(t).padStart(2,\"0\")})),i}(await crypto.subtle.digest(\"SHA-256\",sT(e)),16);class dT{constructor(){sh(this,\"_events\",{}),sh(this,\"addListener\",this.on)}getListeners(e){return this._events[e]?this._events[e].map((e=>e.listener)):[]}on(e,t){this._events[e]||(this._events[e]=[]);const i=this._events[e];-1===this._indexOfListener(i,t)&&i.push({listener:t,once:!1})}once(e,t){this._events[e]||(this._events[e]=[]);const i=this._events[e];-1===this._indexOfListener(i,t)&&i.push({listener:t,once:!0})}off(e,t){if(!this._events[e])return;const i=this._events[e],n=this._indexOfListener(i,t);-1!==n&&i.splice(n,1),0===this._events[e].length&&delete this._events[e]}removeAllListeners(e){e?delete this._events[e]:this._events={}}emit(e){this._events[e]||(this._events[e]=[]);const t=this._events[e].map((e=>e));for(var i=arguments.length,n=new Array(i>1?i-1:0),r=1;r1?t-1:0),n=1;n{t.once&&this.off(e,t.listener);try{t.listener.apply(this,i)}catch(t){console.error(\"safeEmit event:\".concat(e,\" error \").concat(null==t?void 0:t.toString()))}}))}_indexOfListener(e,t){let i=e.length;for(;i--;)if(e[i].listener===t)return i;return-1}}let lT=null;function uT(){if(lT)return lT;if(window.electron)return lT=window.electron;if(!window.require)return null;try{return lT=window.require(\"electron\"),lT}catch(e){return null}}var hT,pT,_T,ET,mT,fT,gT,TT;function ST(e){return zg(e.timeout,\"config.timeout\",0,1e5),zg(e.timeoutFactor,\"config.timeoutFactor\",0,100,!1),zg(e.maxRetryCount,\"config.maxRetryConfig\",0,1/0),zg(e.maxRetryTimeout,\"config.maxRetryTimeout\",0,1/0),!0}function RT(e){if(!Array.isArray(e)||e.length<1)return!1;try{e.forEach((e=>{if(!e.urls)throw Error()}))}catch(e){return!1}return!0}function CT(e){return Xg(e.turnServerURL,\"turnServerURL\"),Xg(e.username,\"username\"),Xg(e.password,\"password\"),e.udpport&&zg(e.udpport,\"udpport\",1,99999,!0),e.forceturn&&Yg(e.forceturn,\"forceturn\"),e.security&&Yg(e.security,\"security\"),e.tcpport&&zg(e.tcpport,\"tcpport\",1,99999,!0),!0}function IT(e){return void 0!==e.level&&qg(e.level,\"level\",[1,2,3]),void 0!==e.delay&&zg(e.delay,\"delay\",0,3e3,!0),!0}function vT(e,t){for(var i=arguments.length,n=new Array(i>2?i-2:0),r=2;r{e.emit(t,...n,i,r)}))}function yT(e,t){if(0===e.getListeners(t).length)return cg.resolve();for(var i=arguments.length,n=new Array(i>2?i-2:0),r=2;r2?i-2:0),r=2;r2?r-2:0),o=2;o{i=e}),(e=>{n=e})),null!==n)throw n;if(null===i)throw new Kg(Hg.UNEXPECTED_ERROR,\"handler is not sync\");return i}!function(e){e.CREATE_CLIENT=\"createClient\",e.CHECK_SYSTEM_REQUIREMENTS=\"checkSystemRequirements\",e.SET_AREA=\"setArea\",e.CHECK_VIDEO_TRACK_IS_ACTIVE=\"checkVideoTrackIsActive\",e.CHECK_AUDIO_TRACK_IS_ACTIVE=\"checkAudioTrackIsActive\",e.CREATE_MIC_AUDIO_TRACK=\"createMicrophoneAudioTrack\",e.CREATE_CUSTOM_AUDIO_TRACK=\"createCustomAudioTrack\",e.CREATE_BUFFER_AUDIO_TRACK=\"createBufferSourceAudioTrack\",e.CREATE_CAM_VIDEO_TRACK=\"createCameraVideoTrack\",e.CREATE_CUSTOM_VIDEO_TRACK=\"createCustomVideoTrack\",e.CREATE_MIC_AND_CAM_TRACKS=\"createMicrophoneAndCameraTracks\",e.CREATE_SCREEN_VIDEO_TRACK=\"createScreenVideoTrack\",e.SET_ENCRYPTION_CONFIG=\"Client.setEncryptionConfig\",e.START_PROXY_SERVER=\"Client.startProxyServer\",e.STOP_PROXY_SERVER=\"Client.stopProxyServer\",e.SET_PROXY_SERVER=\"Client.setProxyServer\",e.SET_TURN_SERVER=\"Client.setTurnServer\",e.SET_CLIENT_ROLE=\"Client.setClientRole\",e.SET_LOW_STREAM_PARAMETER=\"Client.setLowStreamParameter\",e.ENABLE_DUAL_STREAM=\"Client.enableDualStream\",e.DISABLE_DUAL_STREAM=\"Client.disableDualStream\",e.JOIN=\"Client.join\",e.LEAVE=\"Client.leave\",e.PUBLISH=\"Client.publish\",e.UNPUBLISH=\"Client.unpublish\",e.SUBSCRIBE=\"Client.subscribe\",e.MASS_SUBSCRIBE=\"Client.massSubscribe\",e.MASS_UNSUBSCRIBE=\"Client.massUnsubscribe\",e.UNSUBSCRIBE=\"Client.unsubscribe\",e.RENEW_TOKEN=\"Client.renewToken\",e.SET_REMOTE_VIDEO_STREAM_TYPE=\"Client.setRemoteVideoStreamType\",e.SET_STREAM_FALLBACK_OPTION=\"Client.setStreamFallbackOption\",e.ENABLE_AUDIO_VOLUME_INDICATOR=\"Client.enableAudioVolumeIndicator\",e.SEND_CUSTOM_REPORT_MESSAGE=\"Client.sendCustomReportMessage\",e.INSPECT_VIDEO_CONTENT=\"Client.inspectVideoContent\",e.STOP_INSPECT_VIDEO_CONTENT=\"Client.stopInspectVideoContent\",e.JOIN_FALLBACK_TO_PROXY=\"Client._joinFallbackToProxy\",e.DATACHANNEL_FAILBACK=\"Client._datachannelFailback\",e.ON_LIVE_STREAM_WARNING=\"Client.onLiveStreamWarning\",e.ON_LIVE_STREAM_ERROR=\"Client.onLiveStreamingError\",e.START_LIVE_STREAMING=\"Client.startLiveStreaming\",e.SET_LIVE_TRANSCODING=\"Client.setLiveTranscoding\",e.STOP_LIVE_STREAMING=\"Client.stopLiveStreaming\",e.START_CHANNEL_MEDIA_RELAY=\"Client.startChannelMediaRelay\",e.UPDATE_CHANNEL_MEDIA_RELAY=\"Client.updateChannelMediaRelay\",e.STOP_CHANNEL_MEDIA_RELAY=\"Client.stopChannelMediaRelay\",e.REQUEST_CONFIG_DISTRIBUTE=\"_config-distribute-request\",e.SET_CONFIG_DISTRIBUTE=\"_configDistribute\",e.LOCAL_TRACK_SET_MUTED=\"LocalTrack.setMute\",e.LOCAL_AUDIO_TRACK_PLAY=\"LocalAudioTrack.play\",e.LOCAL_AUDIO_TRACK_PLAY_IN_ELEMENT=\"LocalAudioTrack.playInElement\",e.LOCAL_AUDIO_TRACK_STOP=\"LocalAudioTrack.stop\",e.LOCAL_AUDIO_TRACK_SET_VOLUME=\"LocalAudioTrack.setVolume\",e.MIC_AUDIO_TRACK_SET_DEVICE=\"MicrophoneAudioTrack.setDevice\",e.BUFFER_AUDIO_TRACK_START=\"BufferSourceAudioTrack.startProcessAudioBuffer\",e.BUFFER_AUDIO_TRACK_STOP=\"BufferSourceAudioTrack.stopProcessAudioBuffer\",e.BUFFER_AUDIO_TRACK_PAUSE=\"BufferSourceAudioTrack.pauseProcessAudioBuffer\",e.BUFFER_AUDIO_TRACK_RESUME=\"BufferSourceAudioTrack.resumeProcessAudioBuffer\",e.BUFFER_AUDIO_TRACK_SEEK=\"BufferSourceAudioTrack.seekAudioBuffer\",e.LOCAL_VIDEO_TRACK_PLAY=\"LocalVideoTrack.play\",e.LOCAL_VIDEO_TRACK_STOP=\"LocalVideoTrack.stop\",e.LOCAL_VIDEO_TRACK_GET_VIDEO_VISIBLE=\"LocalVideoTrack.getVideoElementVisibleStatus\",e.LOCAL_VIDEO_TRACK_BEAUTY=\"LocalVideoTrack.setBeautyEffect\",e.LOCAL_VIDEO_SEND_SEI_DATA=\"LocalVideoTrack.sendSeiData\",e.CAM_VIDEO_TRACK_SET_DEVICE=\"CameraVideoTrack.setDevice\",e.CAM_VIDEO_TRACK_SET_ENCODER_CONFIG=\"CameraVideoTrack.setEncoderConfiguration\",e.REMOTE_VIDEO_TRACK_PLAY=\"RemoteVideoTrack.play\",e.REMOTE_VIDEO_TRACK_STOP=\"RemoteVideoTrack.stop\",e.REMOTE_VIDEO_TRACK_GET_VIDEO_VISIBLE=\"RemoteVideoTrack.getVideoElementVisibleStatus\",e.REMOTE_AUDIO_TRACK_PLAY=\"RemoteAudioTrack.play\",e.REMOTE_AUDIO_TRACK_STOP=\"RemoteAudioTrack.stop\",e.REMOTE_AUDIO_SET_VOLUME=\"RemoteAudioTrack.setVolume\",e.REMOTE_AUDIO_SET_OUTPUT_DEVICE=\"RemoteAudioTrack.setOutputDevice\",e.GET_MEDIA_STREAM_TRACK=\"Track.getMediaStreamTrack\",e.STREAM_TYPE_CHANGE=\"streamTypeChange\",e.CONNECTION_STATE_CHANGE=\"connectionStateChange\",e.LOAD_CONFIG_FROM_LOCALSTORAGE=\"loadConfigFromLocalStorage\",e.IMAGE_MODERATION_UPLOAD=\"imageModerationUpload\"}(hT||(hT={})),function(e){e.TRACER=\"tracer\"}(pT||(pT={})),function(e){e[e.AUDIENCE_LEVEL_LOW_LATENCY=1]=\"AUDIENCE_LEVEL_LOW_LATENCY\",e[e.AUDIENCE_LEVEL_ULTRA_LOW_LATENCY=2]=\"AUDIENCE_LEVEL_ULTRA_LOW_LATENCY\",e[e.AUDIENCE_LEVEL_SYNC_LATENCY=3]=\"AUDIENCE_LEVEL_SYNC_LATENCY\"}(_T||(_T={})),function(e){e.LEAVE=\"LEAVE\",e.NETWORK_ERROR=\"NETWORK_ERROR\",e.SERVER_ERROR=\"SERVER_ERROR\",e.UID_BANNED=\"UID_BANNED\",e.IP_BANNED=\"IP_BANNED\",e.CHANNEL_BANNED=\"CHANNEL_BANNED\",e.FALLBACK=\"FALLBACK\",e.LICENSE_MISSING=\"LICENSE_MISSING\",e.LICENSE_EXPIRED=\"LICENSE_EXPIRED\",e.LICENSE_MINUTES_EXCEEDED=\"LICENSE_MINUTES_EXCEEDED\",e.LICENSE_PERIOD_INVALID=\"LICENSE_PERIOD_INVALID\",e.LICENSE_MULTIPLE_SDK_SERVICE=\"LICENSE_MULTIPLE_SDK_SERVICE\",e.LICENSE_ILLEGAL=\"LICENSE_ILLEGAL\",e.TOKEN_EXPIRE=\"TOKEN_EXPIRE\"}(ET||(ET={})),function(e){e.CONNECTION_STATE_CHANGE=\"connection-state-change\",e.MEDIA_RECONNECT_START=\"media-reconnect-start\",e.MEDIA_RECONNECT_END=\"media-reconnect-end\",e.IS_USING_CLOUD_PROXY=\"is-using-cloud-proxy\",e.USER_JOINED=\"user-joined\",e.USER_LEAVED=\"user-left\",e.USER_PUBLISHED=\"user-published\",e.USER_UNPUBLISHED=\"user-unpublished\",e.USER_INFO_UPDATED=\"user-info-updated\",e.CLIENT_BANNED=\"client-banned\",e.CHANNEL_MEDIA_RELAY_STATE=\"channel-media-relay-state\",e.CHANNEL_MEDIA_RELAY_EVENT=\"channel-media-relay-event\",e.VOLUME_INDICATOR=\"volume-indicator\",e.CRYPT_ERROR=\"crypt-error\",e.ON_TOKEN_PRIVILEGE_WILL_EXPIRE=\"token-privilege-will-expire\",e.ON_TOKEN_PRIVILEGE_DID_EXPIRE=\"token-privilege-did-expire\",e.NETWORK_QUALITY=\"network-quality\",e.STREAM_TYPE_CHANGED=\"stream-type-changed\",e.STREAM_FALLBACK=\"stream-fallback\",e.RECEIVE_METADATA=\"receive-metadata\",e.STREAM_MESSAGE=\"stream-message\",e.LIVE_STREAMING_ERROR=\"live-streaming-error\",e.LIVE_STREAMING_WARNING=\"live-streaming-warning\",e.INJECT_STREAM_STATUS=\"stream-inject-status\",e.EXCEPTION=\"exception\",e.ERROR=\"error\",e.P2P_LOST=\"p2p_lost\",e.JOIN_FALLBACK_TO_PROXY=\"join-fallback-to-proxy\",e.CHANNEL_FALLBACK_TO_WEBSOCKET=\"channel-fallback-to-websocket\",e.MEDIA_CONNECTION_TYPE_CHANGE=\"media-connection-type-change\",e.PUBLISHED_USER_LIST=\"published-user-list\",e.CONTENT_INSPECT_CONNECTION_STATE_CHANGE=\"content-inspect-connection-state-change\",e.CONTENT_INSPECT_ERROR=\"content-inspect-error\",e.CONTENT_INSPECT_RESULT=\"content-inspect-result\",e.IMAGE_MODERATION_CONNECTION_STATE_CHANGE=\"image-moderation-connection-state-change\"}(mT||(mT={})),function(e){e.NETWORK_ERROR=\"NETWORK_ERROR\",e.SERVER_ERROR=\"SERVER_ERROR\",e.MULTI_IP=\"MULTI_IP\",e.TIMEOUT=\"TIMEOUT\",e.OFFLINE=\"OFFLINE\",e.LEAVE=\"LEAVE\",e.P2P_FAILED=\"P2P_FAILED\",e.FALLBACK=\"FALLBACK\"}(fT||(fT={})),function(e){e.ONLINE=\"ONLINE\",e.OFFLINE=\"OFFLINE\"}(gT||(gT={})),function(e){e.NETWORK_STATE_CHANGE=\"NETWORK_STATE_CHANGE\",e.ONLINE=\"ONLINE\",e.OFFLINE=\"OFFLINE\"}(TT||(TT={}));const wT=new class extends dT{set networkState(e){this.emit(TT.NETWORK_STATE_CHANGE,e,this._networkState),e===gT.ONLINE?this.emit(TT.ONLINE):e===gT.OFFLINE&&(this.onlineWaiter=new cg((e=>{this.once(TT.ONLINE,(()=>{this.onlineWaiter=void 0,e(gT.ONLINE)}))})),this.emit(TT.OFFLINE)),this._networkState=e}get networkState(){return this._networkState}get isOnline(){return this._networkState===gT.ONLINE}constructor(){super(),sh(this,\"_moduleName\",\"network-indicator\"),sh(this,\"_networkState\",gT.ONLINE),sh(this,\"onlineWaiter\",void 0),window.addEventListener(\"online\",(()=>{this.networkState=gT.ONLINE})),window.addEventListener(\"offline\",(()=>{this.networkState=gT.OFFLINE}))}};var OT=De,NT=Je,DT=K,PT=Bi,LT=TypeError,kT=function(e){return function(t,i,n,r){OT(i);var s=NT(t),o=DT(s),a=PT(s),c=e?a-1:0,d=e?-1:1;if(n<2)for(;;){if(c in o){r=o[c],c+=d;break}if(c+=d,e?c<0:a<=c)throw LT(\"Reduce of empty array with no initial value\")}for(;e?c>=0:a>c;c+=d)c in o&&(r=i(r,o[c],c,s));return r}},MT={left:kT(!1),right:kT(!0)}.left;wi({target:\"Array\",proto:!0,forced:!b_&&Ee>79&&Ee<83||!Ih(\"reduce\")},{reduce:function(e){var t=arguments.length;return MT(this,e,t,t>1?arguments[1]:void 0)}});var UT=zi(\"Array\").reduce,xT=l,VT=UT,FT=Array.prototype,BT=i((function(e){var t=e.reduce;return e===FT||xT(FT,e)&&t===FT.reduce?VT:t}));function jT(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function GT(e){for(var t=1;t{-1===t.indexOf(e)&&t.push(e)})),t}function KT(e){void 0!==cg?cg.resolve().then(e):setTimeout(e,0)}function YT(e){return JSON.parse(JSON.stringify(e))}function qT(e){try{return YT(e)}catch(t){return e}}const zT={};function JT(e,t){zT[t]||(zT[t]=!0,e())}function XT(e){const t=window.atob(e),i=new Uint8Array(new ArrayBuffer(t.length));for(let e=0;ee+t.length),0),r=new Uint8Array(new ArrayBuffer(n));let s=0;return t.forEach((e=>{r.set(e,s),s+=e.length})),r}function $T(e){return window.TextEncoder?(new TextEncoder).encode(e).length:e.length}function eS(e){let t=0;return/DingTalk/i.test(navigator.userAgent)&&e.realFormData&&(e=e.realFormData),e.forEach((e=>{t+=\"string\"==typeof e?$T(e):e.size})),t+138}function tS(e){const t=new Kg(Hg.TIMEOUT,\"timeout\");return new cg(((i,n)=>{window.setTimeout((()=>n(t)),e)}))}function iS(e){return new cg((t=>{window.setTimeout(t,e)}))}function nS(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:7,t=arguments.length>1?arguments[1]:void 0;const i=Math.random().toString(16).substr(2,e).toLowerCase();return i.length===e?\"\".concat(t).concat(i):\"\".concat(t).concat(i)+nS(e-i.length,\"\")}function rS(){return nS(32,\"\").toUpperCase()}const sS=()=>{};const oS=new class{constructor(){sh(this,\"fnMap\",new Map)}throttleByKey(e,t,i,n){for(var r=arguments.length,s=new Array(r>4?r-4:0),o=4;o{const e=this.fnMap.get(t);e&&e.fn(...e.args),this.fnMap.delete(t)}),i);this.fnMap.set(t,{fn:e,threshold:i,timer:o,args:s,skipFn:n})}else r.skipFn&&r.skipFn(...r.args),this.fnMap.set(t,GT(GT({},r),{},{fn:e,args:s,skipFn:n}))}else{const r=window.setTimeout((()=>{const e=this.fnMap.get(t);e&&e.fn(...e.args),this.fnMap.delete(t)}),i);this.fnMap.set(t,{fn:e,threshold:i,timer:r,args:s,skipFn:n})}}},aS=oS.throttleByKey.bind(oS);function cS(e){return\"object\"==typeof e&&null!==e&&!(e instanceof RegExp)}function dS(e,t){if(!cS(e)||!cS(t))return t;if(Array.isArray(e)&&!Array.isArray(t)||!Array.isArray(e)&&Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e)){const i=[...e];for(let n=0;n0&&(i[n]=255&e,e>>=8,n++,!t||n!==t););return i}let uS=1,hS=console;class pS{static setLogger(e){hS=e}constructor(e){sh(this,\"lockingPromise\",cg.resolve()),sh(this,\"locks\",0),sh(this,\"name\",\"\"),sh(this,\"lockId\",void 0),this.lockId=uS++,e&&(this.name=e),hS.debug(\"[lock-\".concat(this.name,\"-\").concat(this.lockId,\"] is created.\"))}get isLocked(){return this.locks>0}lock(e){let t;this.locks+=1,hS.debug(\"[lock-\".concat(this.name,\"-\").concat(this.lockId,\"] is locked, current queue \").concat(this.locks,\". \").concat(\"string\"==typeof e?e:\"\"));const i=new cg((i=>{t=()=>{this.locks-=1,hS.debug(\"[lock-\".concat(this.name,\"-\").concat(this.lockId,\"] is not locked, current queue \").concat(this.locks,\". \").concat(\"string\"==typeof e?e:\"\")),i()}})),n=this.lockingPromise.then((()=>t));return this.lockingPromise=this.lockingPromise.then((()=>i)),n}}function _S(e,t){return function(i,n,r){const s=r.value;if(\"function\"!=typeof s)throw new Error(\"Cannot use mutex on object property.\");return r.value=async function(){const i=this[t];if(!i)throw new Error(\"mutex property key \".concat(t,\" doesn't exist on \").concat(e));const r=await i.lock(\"From \".concat(e,\".\").concat(n));try{for(var o=arguments.length,a=new Array(o),c=0;c{await function(e){return new cg((t=>{window.setTimeout(t,e)}))}(s),s*=r.timeoutFactor,s=Math.min(r.maxRetryTimeout,s)};let a=!1;const c=new cg((async(n,s)=>{t=t||(()=>!1),i=i||(()=>!0);for(let c=0;ca=!0,c}let gS=class{constructor(e){sh(this,\"input\",[]),sh(this,\"size\",void 0),this.size=e}add(e){this.input.push(e),this.input.length>this.size&&this.input.splice(0,1)}mean(){var e;return 0===this.input.length?0:BT(e=this.input).call(e,((e,t)=>e+t))/this.input.length}};function TS(e,t){return function(){return e.apply(t,arguments)}}const{toString:SS}=Object.prototype,{getPrototypeOf:RS}=Object,CS=(IS=Object.create(null),e=>{const t=SS.call(e);return IS[t]||(IS[t]=t.slice(8,-1).toLowerCase())});var IS;const vS=e=>(e=e.toLowerCase(),t=>CS(t)===e),yS=e=>t=>typeof t===e,{isArray:AS}=Array,bS=yS(\"undefined\");const wS=vS(\"ArrayBuffer\");const OS=yS(\"string\"),NS=yS(\"function\"),DS=yS(\"number\"),PS=e=>null!==e&&\"object\"==typeof e,LS=e=>{if(\"object\"!==CS(e))return!1;const t=RS(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Symbol.toStringTag in e||Symbol.iterator in e)},kS=vS(\"Date\"),MS=vS(\"File\"),US=vS(\"Blob\"),xS=vS(\"FileList\"),VS=vS(\"URLSearchParams\");function FS(e,t,{allOwnKeys:i=!1}={}){if(null==e)return;let n,r;if(\"object\"!=typeof e&&(e=[e]),AS(e))for(n=0,r=e.length;n0;)if(n=i[r],t===n.toLowerCase())return n;return null}const jS=\"undefined\"!=typeof globalThis?globalThis:\"undefined\"!=typeof self?self:\"undefined\"!=typeof window?window:global,GS=e=>!bS(e)&&e!==jS;const WS=(HS=\"undefined\"!=typeof Uint8Array&&RS(Uint8Array),e=>HS&&e instanceof HS);var HS;const KS=vS(\"HTMLFormElement\"),YS=(({hasOwnProperty:e})=>(t,i)=>e.call(t,i))(Object.prototype),qS=vS(\"RegExp\"),zS=(e,t)=>{const i=Object.getOwnPropertyDescriptors(e),n={};FS(i,((i,r)=>{let s;!1!==(s=t(i,r,e))&&(n[r]=s||i)})),Object.defineProperties(e,n)},JS=\"abcdefghijklmnopqrstuvwxyz\",XS=\"0123456789\",QS={DIGIT:XS,ALPHA:JS,ALPHA_DIGIT:JS+JS.toUpperCase()+XS};const ZS=vS(\"AsyncFunction\");var $S={isArray:AS,isArrayBuffer:wS,isBuffer:function(e){return null!==e&&!bS(e)&&null!==e.constructor&&!bS(e.constructor)&&NS(e.constructor.isBuffer)&&e.constructor.isBuffer(e)},isFormData:e=>{let t;return e&&(\"function\"==typeof FormData&&e instanceof FormData||NS(e.append)&&(\"formdata\"===(t=CS(e))||\"object\"===t&&NS(e.toString)&&\"[object FormData]\"===e.toString()))},isArrayBufferView:function(e){let t;return t=\"undefined\"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&wS(e.buffer),t},isString:OS,isNumber:DS,isBoolean:e=>!0===e||!1===e,isObject:PS,isPlainObject:LS,isUndefined:bS,isDate:kS,isFile:MS,isBlob:US,isRegExp:qS,isFunction:NS,isStream:e=>PS(e)&&NS(e.pipe),isURLSearchParams:VS,isTypedArray:WS,isFileList:xS,forEach:FS,merge:function e(){const{caseless:t}=GS(this)&&this||{},i={},n=(n,r)=>{const s=t&&BS(i,r)||r;LS(i[s])&&LS(n)?i[s]=e(i[s],n):LS(n)?i[s]=e({},n):AS(n)?i[s]=n.slice():i[s]=n};for(let e=0,t=arguments.length;e(FS(t,((t,n)=>{i&&NS(t)?e[n]=TS(t,i):e[n]=t}),{allOwnKeys:n}),e),trim:e=>e.trim?e.trim():e.replace(/^[\\s\\uFEFF\\xA0]+|[\\s\\uFEFF\\xA0]+$/g,\"\"),stripBOM:e=>(65279===e.charCodeAt(0)&&(e=e.slice(1)),e),inherits:(e,t,i,n)=>{e.prototype=Object.create(t.prototype,n),e.prototype.constructor=e,Object.defineProperty(e,\"super\",{value:t.prototype}),i&&Object.assign(e.prototype,i)},toFlatObject:(e,t,i,n)=>{let r,s,o;const a={};if(t=t||{},null==e)return t;do{for(r=Object.getOwnPropertyNames(e),s=r.length;s-- >0;)o=r[s],n&&!n(o,e,t)||a[o]||(t[o]=e[o],a[o]=!0);e=!1!==i&&RS(e)}while(e&&(!i||i(e,t))&&e!==Object.prototype);return t},kindOf:CS,kindOfTest:vS,endsWith:(e,t,i)=>{e=String(e),(void 0===i||i>e.length)&&(i=e.length),i-=t.length;const n=e.indexOf(t,i);return-1!==n&&n===i},toArray:e=>{if(!e)return null;if(AS(e))return e;let t=e.length;if(!DS(t))return null;const i=new Array(t);for(;t-- >0;)i[t]=e[t];return i},forEachEntry:(e,t)=>{const i=(e&&e[Symbol.iterator]).call(e);let n;for(;(n=i.next())&&!n.done;){const i=n.value;t.call(e,i[0],i[1])}},matchAll:(e,t)=>{let i;const n=[];for(;null!==(i=e.exec(t));)n.push(i);return n},isHTMLForm:KS,hasOwnProperty:YS,hasOwnProp:YS,reduceDescriptors:zS,freezeMethods:e=>{zS(e,((t,i)=>{if(NS(e)&&-1!==[\"arguments\",\"caller\",\"callee\"].indexOf(i))return!1;const n=e[i];NS(n)&&(t.enumerable=!1,\"writable\"in t?t.writable=!1:t.set||(t.set=()=>{throw Error(\"Can not rewrite read-only method '\"+i+\"'\")}))}))},toObjectSet:(e,t)=>{const i={},n=e=>{e.forEach((e=>{i[e]=!0}))};return AS(e)?n(e):n(String(e).split(t)),i},toCamelCase:e=>e.toLowerCase().replace(/[-_\\s]([a-z\\d])(\\w*)/g,(function(e,t,i){return t.toUpperCase()+i})),noop:()=>{},toFiniteNumber:(e,t)=>(e=+e,Number.isFinite(e)?e:t),findKey:BS,global:jS,isContextDefined:GS,ALPHABET:QS,generateString:(e=16,t=QS.ALPHA_DIGIT)=>{let i=\"\";const{length:n}=t;for(;e--;)i+=t[Math.random()*n|0];return i},isSpecCompliantForm:function(e){return!!(e&&NS(e.append)&&\"FormData\"===e[Symbol.toStringTag]&&e[Symbol.iterator])},toJSONObject:e=>{const t=new Array(10),i=(e,n)=>{if(PS(e)){if(t.indexOf(e)>=0)return;if(!(\"toJSON\"in e)){t[n]=e;const r=AS(e)?[]:{};return FS(e,((e,t)=>{const s=i(e,n+1);!bS(s)&&(r[t]=s)})),t[n]=void 0,r}}return e};return i(e,0)},isAsyncFn:ZS,isThenable:e=>e&&(PS(e)||NS(e))&&NS(e.then)&&NS(e.catch)};function eR(e,t,i,n,r){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=(new Error).stack,this.message=e,this.name=\"AxiosError\",t&&(this.code=t),i&&(this.config=i),n&&(this.request=n),r&&(this.response=r)}$S.inherits(eR,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:$S.toJSONObject(this.config),code:this.code,status:this.response&&this.response.status?this.response.status:null}}});const tR=eR.prototype,iR={};[\"ERR_BAD_OPTION_VALUE\",\"ERR_BAD_OPTION\",\"ECONNABORTED\",\"ETIMEDOUT\",\"ERR_NETWORK\",\"ERR_FR_TOO_MANY_REDIRECTS\",\"ERR_DEPRECATED\",\"ERR_BAD_RESPONSE\",\"ERR_BAD_REQUEST\",\"ERR_CANCELED\",\"ERR_NOT_SUPPORT\",\"ERR_INVALID_URL\"].forEach((e=>{iR[e]={value:e}})),Object.defineProperties(eR,iR),Object.defineProperty(tR,\"isAxiosError\",{value:!0}),eR.from=(e,t,i,n,r,s)=>{const o=Object.create(tR);return $S.toFlatObject(e,o,(function(e){return e!==Error.prototype}),(e=>\"isAxiosError\"!==e)),eR.call(o,e.message,t,i,n,r),o.cause=e,o.name=e.name,s&&Object.assign(o,s),o};function nR(e){return $S.isPlainObject(e)||$S.isArray(e)}function rR(e){return $S.endsWith(e,\"[]\")?e.slice(0,-2):e}function sR(e,t,i){return e?e.concat(t).map((function(e,t){return e=rR(e),!i&&t?\"[\"+e+\"]\":e})).join(i?\".\":\"\"):t}const oR=$S.toFlatObject($S,{},null,(function(e){return/^is[A-Z]/.test(e)}));function aR(e,t,i){if(!$S.isObject(e))throw new TypeError(\"target must be an object\");t=t||new FormData;const n=(i=$S.toFlatObject(i,{metaTokens:!0,dots:!1,indexes:!1},!1,(function(e,t){return!$S.isUndefined(t[e])}))).metaTokens,r=i.visitor||d,s=i.dots,o=i.indexes,a=(i.Blob||\"undefined\"!=typeof Blob&&Blob)&&$S.isSpecCompliantForm(t);if(!$S.isFunction(r))throw new TypeError(\"visitor must be a function\");function c(e){if(null===e)return\"\";if($S.isDate(e))return e.toISOString();if(!a&&$S.isBlob(e))throw new eR(\"Blob is not supported. Use a Buffer instead.\");return $S.isArrayBuffer(e)||$S.isTypedArray(e)?a&&\"function\"==typeof Blob?new Blob([e]):Buffer.from(e):e}function d(e,i,r){let a=e;if(e&&!r&&\"object\"==typeof e)if($S.endsWith(i,\"{}\"))i=n?i:i.slice(0,-2),e=JSON.stringify(e);else if($S.isArray(e)&&function(e){return $S.isArray(e)&&!e.some(nR)}(e)||($S.isFileList(e)||$S.endsWith(i,\"[]\"))&&(a=$S.toArray(e)))return i=rR(i),a.forEach((function(e,n){!$S.isUndefined(e)&&null!==e&&t.append(!0===o?sR([i],n,s):null===o?i:i+\"[]\",c(e))})),!1;return!!nR(e)||(t.append(sR(r,i,s),c(e)),!1)}const l=[],u=Object.assign(oR,{defaultVisitor:d,convertValue:c,isVisitable:nR});if(!$S.isObject(e))throw new TypeError(\"data must be an object\");return function e(i,n){if(!$S.isUndefined(i)){if(-1!==l.indexOf(i))throw Error(\"Circular reference detected in \"+n.join(\".\"));l.push(i),$S.forEach(i,(function(i,s){!0===(!($S.isUndefined(i)||null===i)&&r.call(t,i,$S.isString(s)?s.trim():s,n,u))&&e(i,n?n.concat(s):[s])})),l.pop()}}(e),t}function cR(e){const t={\"!\":\"%21\",\"'\":\"%27\",\"(\":\"%28\",\")\":\"%29\",\"~\":\"%7E\",\"%20\":\"+\",\"%00\":\"\\0\"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,(function(e){return t[e]}))}function dR(e,t){this._pairs=[],e&&aR(e,this,t)}const lR=dR.prototype;function uR(e){return encodeURIComponent(e).replace(/%3A/gi,\":\").replace(/%24/g,\"$\").replace(/%2C/gi,\",\").replace(/%20/g,\"+\").replace(/%5B/gi,\"[\").replace(/%5D/gi,\"]\")}function hR(e,t,i){if(!t)return e;const n=i&&i.encode||uR,r=i&&i.serialize;let s;if(s=r?r(t,i):$S.isURLSearchParams(t)?t.toString():new dR(t,i).toString(n),s){const t=e.indexOf(\"#\");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf(\"?\")?\"?\":\"&\")+s}return e}lR.append=function(e,t){this._pairs.push([e,t])},lR.toString=function(e){const t=e?function(t){return e.call(this,t,cR)}:cR;return this._pairs.map((function(e){return t(e[0])+\"=\"+t(e[1])}),\"\").join(\"&\")};var pR=class{constructor(){this.handlers=[]}use(e,t,i){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!i&&i.synchronous,runWhen:i?i.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){$S.forEach(this.handlers,(function(t){null!==t&&e(t)}))}},_R={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},ER={isBrowser:!0,classes:{URLSearchParams:\"undefined\"!=typeof URLSearchParams?URLSearchParams:dR,FormData:\"undefined\"!=typeof FormData?FormData:null,Blob:\"undefined\"!=typeof Blob?Blob:null},protocols:[\"http\",\"https\",\"file\",\"blob\",\"url\",\"data\"]};const mR=\"undefined\"!=typeof window&&\"undefined\"!=typeof document,fR=(gR=\"undefined\"!=typeof navigator&&navigator.product,mR&&[\"ReactNative\",\"NativeScript\",\"NS\"].indexOf(gR)<0);var gR;const TR=\"undefined\"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&\"function\"==typeof self.importScripts;var SR={...Object.freeze({__proto__:null,hasBrowserEnv:mR,hasStandardBrowserEnv:fR,hasStandardBrowserWebWorkerEnv:TR}),...ER};function RR(e){function t(e,i,n,r){let s=e[r++];if(\"__proto__\"===s)return!0;const o=Number.isFinite(+s),a=r>=e.length;if(s=!s&&$S.isArray(n)?n.length:s,a)return $S.hasOwnProp(n,s)?n[s]=[n[s],i]:n[s]=i,!o;n[s]&&$S.isObject(n[s])||(n[s]=[]);return t(e,i,n[s],r)&&$S.isArray(n[s])&&(n[s]=function(e){const t={},i=Object.keys(e);let n;const r=i.length;let s;for(n=0;n{t(function(e){return $S.matchAll(/\\w+|\\[(\\w*)]/g,e).map((e=>\"[]\"===e[0]?\"\":e[1]||e[0]))}(e),n,i,0)})),i}return null}const CR={transitional:_R,adapter:[\"xhr\",\"http\"],transformRequest:[function(e,t){const i=t.getContentType()||\"\",n=i.indexOf(\"application/json\")>-1,r=$S.isObject(e);r&&$S.isHTMLForm(e)&&(e=new FormData(e));if($S.isFormData(e))return n?JSON.stringify(RR(e)):e;if($S.isArrayBuffer(e)||$S.isBuffer(e)||$S.isStream(e)||$S.isFile(e)||$S.isBlob(e))return e;if($S.isArrayBufferView(e))return e.buffer;if($S.isURLSearchParams(e))return t.setContentType(\"application/x-www-form-urlencoded;charset=utf-8\",!1),e.toString();let s;if(r){if(i.indexOf(\"application/x-www-form-urlencoded\")>-1)return function(e,t){return aR(e,new SR.classes.URLSearchParams,Object.assign({visitor:function(e,t,i,n){return SR.isNode&&$S.isBuffer(e)?(this.append(t,e.toString(\"base64\")),!1):n.defaultVisitor.apply(this,arguments)}},t))}(e,this.formSerializer).toString();if((s=$S.isFileList(e))||i.indexOf(\"multipart/form-data\")>-1){const t=this.env&&this.env.FormData;return aR(s?{\"files[]\":e}:e,t&&new t,this.formSerializer)}}return r||n?(t.setContentType(\"application/json\",!1),function(e,t,i){if($S.isString(e))try{return(t||JSON.parse)(e),$S.trim(e)}catch(e){if(\"SyntaxError\"!==e.name)throw e}return(i||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=this.transitional||CR.transitional,i=t&&t.forcedJSONParsing,n=\"json\"===this.responseType;if(e&&$S.isString(e)&&(i&&!this.responseType||n)){const i=!(t&&t.silentJSONParsing)&&n;try{return JSON.parse(e)}catch(e){if(i){if(\"SyntaxError\"===e.name)throw eR.from(e,eR.ERR_BAD_RESPONSE,this,null,this.response);throw e}}}return e}],timeout:0,xsrfCookieName:\"XSRF-TOKEN\",xsrfHeaderName:\"X-XSRF-TOKEN\",maxContentLength:-1,maxBodyLength:-1,env:{FormData:SR.classes.FormData,Blob:SR.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:\"application/json, text/plain, */*\",\"Content-Type\":void 0}}};$S.forEach([\"delete\",\"get\",\"head\",\"post\",\"put\",\"patch\"],(e=>{CR.headers[e]={}}));var IR=CR;const vR=$S.toObjectSet([\"age\",\"authorization\",\"content-length\",\"content-type\",\"etag\",\"expires\",\"from\",\"host\",\"if-modified-since\",\"if-unmodified-since\",\"last-modified\",\"location\",\"max-forwards\",\"proxy-authorization\",\"referer\",\"retry-after\",\"user-agent\"]);const yR=Symbol(\"internals\");function AR(e){return e&&String(e).trim().toLowerCase()}function bR(e){return!1===e||null==e?e:$S.isArray(e)?e.map(bR):String(e)}function wR(e,t,i,n,r){return $S.isFunction(n)?n.call(this,t,i):(r&&(t=i),$S.isString(t)?$S.isString(n)?-1!==t.indexOf(n):$S.isRegExp(n)?n.test(t):void 0:void 0)}class OR{constructor(e){e&&this.set(e)}set(e,t,i){const n=this;function r(e,t,i){const r=AR(t);if(!r)throw new Error(\"header name must be a non-empty string\");const s=$S.findKey(n,r);(!s||void 0===n[s]||!0===i||void 0===i&&!1!==n[s])&&(n[s||t]=bR(e))}const s=(e,t)=>$S.forEach(e,((e,i)=>r(e,i,t)));return $S.isPlainObject(e)||e instanceof this.constructor?s(e,t):$S.isString(e)&&(e=e.trim())&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim())?s((e=>{const t={};let i,n,r;return e&&e.split(\"\\n\").forEach((function(e){r=e.indexOf(\":\"),i=e.substring(0,r).trim().toLowerCase(),n=e.substring(r+1).trim(),!i||t[i]&&vR[i]||(\"set-cookie\"===i?t[i]?t[i].push(n):t[i]=[n]:t[i]=t[i]?t[i]+\", \"+n:n)})),t})(e),t):null!=e&&r(t,e,i),this}get(e,t){if(e=AR(e)){const i=$S.findKey(this,e);if(i){const e=this[i];if(!t)return e;if(!0===t)return function(e){const t=Object.create(null),i=/([^\\s,;=]+)\\s*(?:=\\s*([^,;]+))?/g;let n;for(;n=i.exec(e);)t[n[1]]=n[2];return t}(e);if($S.isFunction(t))return t.call(this,e,i);if($S.isRegExp(t))return t.exec(e);throw new TypeError(\"parser must be boolean|regexp|function\")}}}has(e,t){if(e=AR(e)){const i=$S.findKey(this,e);return!(!i||void 0===this[i]||t&&!wR(0,this[i],i,t))}return!1}delete(e,t){const i=this;let n=!1;function r(e){if(e=AR(e)){const r=$S.findKey(i,e);!r||t&&!wR(0,i[r],r,t)||(delete i[r],n=!0)}}return $S.isArray(e)?e.forEach(r):r(e),n}clear(e){const t=Object.keys(this);let i=t.length,n=!1;for(;i--;){const r=t[i];e&&!wR(0,this[r],r,e,!0)||(delete this[r],n=!0)}return n}normalize(e){const t=this,i={};return $S.forEach(this,((n,r)=>{const s=$S.findKey(i,r);if(s)return t[s]=bR(n),void delete t[r];const o=e?function(e){return e.trim().toLowerCase().replace(/([a-z\\d])(\\w*)/g,((e,t,i)=>t.toUpperCase()+i))}(r):String(r).trim();o!==r&&delete t[r],t[o]=bR(n),i[o]=!0})),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return $S.forEach(this,((i,n)=>{null!=i&&!1!==i&&(t[n]=e&&$S.isArray(i)?i.join(\", \"):i)})),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map((([e,t])=>e+\": \"+t)).join(\"\\n\")}get[Symbol.toStringTag](){return\"AxiosHeaders\"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...t){const i=new this(e);return t.forEach((e=>i.set(e))),i}static accessor(e){const t=(this[yR]=this[yR]={accessors:{}}).accessors,i=this.prototype;function n(e){const n=AR(e);t[n]||(!function(e,t){const i=$S.toCamelCase(\" \"+t);[\"get\",\"set\",\"has\"].forEach((n=>{Object.defineProperty(e,n+i,{value:function(e,i,r){return this[n].call(this,t,e,i,r)},configurable:!0})}))}(i,e),t[n]=!0)}return $S.isArray(e)?e.forEach(n):n(e),this}}OR.accessor([\"Content-Type\",\"Content-Length\",\"Accept\",\"Accept-Encoding\",\"User-Agent\",\"Authorization\"]),$S.reduceDescriptors(OR.prototype,(({value:e},t)=>{let i=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(e){this[i]=e}}})),$S.freezeMethods(OR);var NR=OR;function DR(e,t){const i=this||IR,n=t||i,r=NR.from(n.headers);let s=n.data;return $S.forEach(e,(function(e){s=e.call(i,s,r.normalize(),t?t.status:void 0)})),r.normalize(),s}function PR(e){return!(!e||!e.__CANCEL__)}function LR(e,t,i){eR.call(this,null==e?\"canceled\":e,eR.ERR_CANCELED,t,i),this.name=\"CanceledError\"}$S.inherits(LR,eR,{__CANCEL__:!0});var kR=SR.hasStandardBrowserEnv?{write(e,t,i,n,r,s){const o=[e+\"=\"+encodeURIComponent(t)];$S.isNumber(i)&&o.push(\"expires=\"+new Date(i).toGMTString()),$S.isString(n)&&o.push(\"path=\"+n),$S.isString(r)&&o.push(\"domain=\"+r),!0===s&&o.push(\"secure\"),document.cookie=o.join(\"; \")},read(e){const t=document.cookie.match(new RegExp(\"(^|;\\\\s*)(\"+e+\")=([^;]*)\"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,\"\",Date.now()-864e5)}}:{write(){},read:()=>null,remove(){}};function MR(e,t){return e&&!function(e){return/^([a-z][a-z\\d+\\-.]*:)?\\/\\//i.test(e)}(t)?function(e,t){return t?e.replace(/\\/?\\/$/,\"\")+\"/\"+t.replace(/^\\/+/,\"\"):e}(e,t):t}var UR=SR.hasStandardBrowserEnv?function(){const e=/(msie|trident)/i.test(navigator.userAgent),t=document.createElement(\"a\");let i;function n(i){let n=i;return e&&(t.setAttribute(\"href\",n),n=t.href),t.setAttribute(\"href\",n),{href:t.href,protocol:t.protocol?t.protocol.replace(/:$/,\"\"):\"\",host:t.host,search:t.search?t.search.replace(/^\\?/,\"\"):\"\",hash:t.hash?t.hash.replace(/^#/,\"\"):\"\",hostname:t.hostname,port:t.port,pathname:\"/\"===t.pathname.charAt(0)?t.pathname:\"/\"+t.pathname}}return i=n(window.location.href),function(e){const t=$S.isString(e)?n(e):e;return t.protocol===i.protocol&&t.host===i.host}}():function(){return!0};function xR(e,t){let i=0;const n=function(e,t){e=e||10;const i=new Array(e),n=new Array(e);let r,s=0,o=0;return t=void 0!==t?t:1e3,function(a){const c=Date.now(),d=n[o];r||(r=c),i[s]=a,n[s]=c;let l=o,u=0;for(;l!==s;)u+=i[l++],l%=e;if(s=(s+1)%e,s===o&&(o=(o+1)%e),c-r{const s=r.loaded,o=r.lengthComputable?r.total:void 0,a=s-i,c=n(a);i=s;const d={loaded:s,total:o,progress:o?s/o:void 0,bytes:a,rate:c||void 0,estimated:c&&o&&s<=o?(o-s)/c:void 0,event:r};d[t?\"download\":\"upload\"]=!0,e(d)}}var VR=\"undefined\"!=typeof XMLHttpRequest&&function(e){return new Promise((function(t,i){let n=e.data;const r=NR.from(e.headers).normalize();let s,o,{responseType:a,withXSRFToken:c}=e;function d(){e.cancelToken&&e.cancelToken.unsubscribe(s),e.signal&&e.signal.removeEventListener(\"abort\",s)}if($S.isFormData(n))if(SR.hasStandardBrowserEnv||SR.hasStandardBrowserWebWorkerEnv)r.setContentType(!1);else if(!1!==(o=r.getContentType())){const[e,...t]=o?o.split(\";\").map((e=>e.trim())).filter(Boolean):[];r.setContentType([e||\"multipart/form-data\",...t].join(\"; \"))}let l=new XMLHttpRequest;if(e.auth){const t=e.auth.username||\"\",i=e.auth.password?unescape(encodeURIComponent(e.auth.password)):\"\";r.set(\"Authorization\",\"Basic \"+btoa(t+\":\"+i))}const u=MR(e.baseURL,e.url);function h(){if(!l)return;const n=NR.from(\"getAllResponseHeaders\"in l&&l.getAllResponseHeaders());!function(e,t,i){const n=i.config.validateStatus;i.status&&n&&!n(i.status)?t(new eR(\"Request failed with status code \"+i.status,[eR.ERR_BAD_REQUEST,eR.ERR_BAD_RESPONSE][Math.floor(i.status/100)-4],i.config,i.request,i)):e(i)}((function(e){t(e),d()}),(function(e){i(e),d()}),{data:a&&\"text\"!==a&&\"json\"!==a?l.response:l.responseText,status:l.status,statusText:l.statusText,headers:n,config:e,request:l}),l=null}if(l.open(e.method.toUpperCase(),hR(u,e.params,e.paramsSerializer),!0),l.timeout=e.timeout,\"onloadend\"in l?l.onloadend=h:l.onreadystatechange=function(){l&&4===l.readyState&&(0!==l.status||l.responseURL&&0===l.responseURL.indexOf(\"file:\"))&&setTimeout(h)},l.onabort=function(){l&&(i(new eR(\"Request aborted\",eR.ECONNABORTED,e,l)),l=null)},l.onerror=function(){i(new eR(\"Network Error\",eR.ERR_NETWORK,e,l)),l=null},l.ontimeout=function(){let t=e.timeout?\"timeout of \"+e.timeout+\"ms exceeded\":\"timeout exceeded\";const n=e.transitional||_R;e.timeoutErrorMessage&&(t=e.timeoutErrorMessage),i(new eR(t,n.clarifyTimeoutError?eR.ETIMEDOUT:eR.ECONNABORTED,e,l)),l=null},SR.hasStandardBrowserEnv&&(c&&$S.isFunction(c)&&(c=c(e)),c||!1!==c&&UR(u))){const t=e.xsrfHeaderName&&e.xsrfCookieName&&kR.read(e.xsrfCookieName);t&&r.set(e.xsrfHeaderName,t)}void 0===n&&r.setContentType(null),\"setRequestHeader\"in l&&$S.forEach(r.toJSON(),(function(e,t){l.setRequestHeader(t,e)})),$S.isUndefined(e.withCredentials)||(l.withCredentials=!!e.withCredentials),a&&\"json\"!==a&&(l.responseType=e.responseType),\"function\"==typeof e.onDownloadProgress&&l.addEventListener(\"progress\",xR(e.onDownloadProgress,!0)),\"function\"==typeof e.onUploadProgress&&l.upload&&l.upload.addEventListener(\"progress\",xR(e.onUploadProgress)),(e.cancelToken||e.signal)&&(s=t=>{l&&(i(!t||t.type?new LR(null,e,l):t),l.abort(),l=null)},e.cancelToken&&e.cancelToken.subscribe(s),e.signal&&(e.signal.aborted?s():e.signal.addEventListener(\"abort\",s)));const p=function(e){const t=/^([-+\\w]{1,25})(:?\\/\\/|:)/.exec(e);return t&&t[1]||\"\"}(u);p&&-1===SR.protocols.indexOf(p)?i(new eR(\"Unsupported protocol \"+p+\":\",eR.ERR_BAD_REQUEST,e)):l.send(n||null)}))};const FR={http:null,xhr:VR};$S.forEach(FR,((e,t)=>{if(e){try{Object.defineProperty(e,\"name\",{value:t})}catch(e){}Object.defineProperty(e,\"adapterName\",{value:t})}}));const BR=e=>`- ${e}`,jR=e=>$S.isFunction(e)||null===e||!1===e;var GR={getAdapter:e=>{e=$S.isArray(e)?e:[e];const{length:t}=e;let i,n;const r={};for(let s=0;s`adapter ${e} `+(!1===t?\"is not supported by the environment\":\"is not available in the build\")));throw new eR(\"There is no suitable adapter to dispatch the request \"+(t?e.length>1?\"since :\\n\"+e.map(BR).join(\"\\n\"):\" \"+BR(e[0]):\"as no adapter specified\"),\"ERR_NOT_SUPPORT\")}return n},adapters:FR};function WR(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new LR(null,e)}function HR(e){WR(e),e.headers=NR.from(e.headers),e.data=DR.call(e,e.transformRequest),-1!==[\"post\",\"put\",\"patch\"].indexOf(e.method)&&e.headers.setContentType(\"application/x-www-form-urlencoded\",!1);return GR.getAdapter(e.adapter||IR.adapter)(e).then((function(t){return WR(e),t.data=DR.call(e,e.transformResponse,t),t.headers=NR.from(t.headers),t}),(function(t){return PR(t)||(WR(e),t&&t.response&&(t.response.data=DR.call(e,e.transformResponse,t.response),t.response.headers=NR.from(t.response.headers))),Promise.reject(t)}))}const KR=e=>e instanceof NR?e.toJSON():e;function YR(e,t){t=t||{};const i={};function n(e,t,i){return $S.isPlainObject(e)&&$S.isPlainObject(t)?$S.merge.call({caseless:i},e,t):$S.isPlainObject(t)?$S.merge({},t):$S.isArray(t)?t.slice():t}function r(e,t,i){return $S.isUndefined(t)?$S.isUndefined(e)?void 0:n(void 0,e,i):n(e,t,i)}function s(e,t){if(!$S.isUndefined(t))return n(void 0,t)}function o(e,t){return $S.isUndefined(t)?$S.isUndefined(e)?void 0:n(void 0,e):n(void 0,t)}function a(i,r,s){return s in t?n(i,r):s in e?n(void 0,i):void 0}const c={url:s,method:s,data:s,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,withXSRFToken:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:a,headers:(e,t)=>r(KR(e),KR(t),!0)};return $S.forEach(Object.keys(Object.assign({},e,t)),(function(n){const s=c[n]||r,o=s(e[n],t[n],n);$S.isUndefined(o)&&s!==a||(i[n]=o)})),i}const qR=\"1.6.7\",zR={};[\"object\",\"boolean\",\"number\",\"function\",\"string\",\"symbol\"].forEach(((e,t)=>{zR[e]=function(i){return typeof i===e||\"a\"+(t<1?\"n \":\" \")+e}}));const JR={};zR.transitional=function(e,t,i){function n(e,t){return\"[Axios v\"+qR+\"] Transitional option '\"+e+\"'\"+t+(i?\". \"+i:\"\")}return(i,r,s)=>{if(!1===e)throw new eR(n(r,\" has been removed\"+(t?\" in \"+t:\"\")),eR.ERR_DEPRECATED);return t&&!JR[r]&&(JR[r]=!0,console.warn(n(r,\" has been deprecated since v\"+t+\" and will be removed in the near future\"))),!e||e(i,r,s)}};var XR={assertOptions:function(e,t,i){if(\"object\"!=typeof e)throw new eR(\"options must be an object\",eR.ERR_BAD_OPTION_VALUE);const n=Object.keys(e);let r=n.length;for(;r-- >0;){const s=n[r],o=t[s];if(o){const t=e[s],i=void 0===t||o(t,s,e);if(!0!==i)throw new eR(\"option \"+s+\" must be \"+i,eR.ERR_BAD_OPTION_VALUE)}else if(!0!==i)throw new eR(\"Unknown option \"+s,eR.ERR_BAD_OPTION)}},validators:zR};const QR=XR.validators;let ZR=class{constructor(e){this.defaults=e,this.interceptors={request:new pR,response:new pR}}async request(e,t){try{return await this._request(e,t)}catch(e){if(e instanceof Error){let t;Error.captureStackTrace?Error.captureStackTrace(t={}):t=new Error;const i=t.stack?t.stack.replace(/^.+\\n/,\"\"):\"\";e.stack?i&&!String(e.stack).endsWith(i.replace(/^.+\\n.+\\n/,\"\"))&&(e.stack+=\"\\n\"+i):e.stack=i}throw e}}_request(e,t){\"string\"==typeof e?(t=t||{}).url=e:t=e||{},t=YR(this.defaults,t);const{transitional:i,paramsSerializer:n,headers:r}=t;void 0!==i&&XR.assertOptions(i,{silentJSONParsing:QR.transitional(QR.boolean),forcedJSONParsing:QR.transitional(QR.boolean),clarifyTimeoutError:QR.transitional(QR.boolean)},!1),null!=n&&($S.isFunction(n)?t.paramsSerializer={serialize:n}:XR.assertOptions(n,{encode:QR.function,serialize:QR.function},!0)),t.method=(t.method||this.defaults.method||\"get\").toLowerCase();let s=r&&$S.merge(r.common,r[t.method]);r&&$S.forEach([\"delete\",\"get\",\"head\",\"post\",\"put\",\"patch\",\"common\"],(e=>{delete r[e]})),t.headers=NR.concat(s,r);const o=[];let a=!0;this.interceptors.request.forEach((function(e){\"function\"==typeof e.runWhen&&!1===e.runWhen(t)||(a=a&&e.synchronous,o.unshift(e.fulfilled,e.rejected))}));const c=[];let d;this.interceptors.response.forEach((function(e){c.push(e.fulfilled,e.rejected)}));let l,u=0;if(!a){const e=[HR.bind(this),void 0];for(e.unshift.apply(e,o),e.push.apply(e,c),l=e.length,d=Promise.resolve(t);u{if(!i._listeners)return;let t=i._listeners.length;for(;t-- >0;)i._listeners[t](e);i._listeners=null})),this.promise.then=e=>{let t;const n=new Promise((e=>{i.subscribe(e),t=e})).then(e);return n.cancel=function(){i.unsubscribe(t)},n},e((function(e,n,r){i.reason||(i.reason=new LR(e,n,r),t(i.reason))}))}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}static source(){let e;return{token:new eC((function(t){e=t})),cancel:e}}}var tC=eC;const iC={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(iC).forEach((([e,t])=>{iC[t]=e}));var nC=iC;const rC=function e(t){const i=new $R(t),n=TS($R.prototype.request,i);return $S.extend(n,$R.prototype,i,{allOwnKeys:!0}),$S.extend(n,i,null,{allOwnKeys:!0}),n.create=function(i){return e(YR(t,i))},n}(IR);rC.Axios=$R,rC.CanceledError=LR,rC.CancelToken=tC,rC.isCancel=PR,rC.VERSION=qR,rC.toFormData=aR,rC.AxiosError=eR,rC.Cancel=rC.CanceledError,rC.all=function(e){return Promise.all(e)},rC.spread=function(e){return function(t){return e.apply(null,t)}},rC.isAxiosError=function(e){return $S.isObject(e)&&!0===e.isAxiosError},rC.mergeConfig=YR,rC.AxiosHeaders=NR,rC.formToJSON=e=>RR($S.isHTMLForm(e)?new FormData(e):e),rC.getAdapter=GR.getAdapter,rC.HttpStatusCode=nC,rC.default=rC;var sC=rC;function oC(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function aC(e){for(var t=1;t{t.responseType=t.responseType||\"json\",t.data&&!i?(t.data=JSON.stringify(t.data),dC+=$T(t.data)):i&&(t.data.size?dC+=t.data.size:t.data instanceof FormData?dC+=eS(t.data):dC+=$T(JSON.stringify(t.data))),t.headers=t.headers||{},t.headers[\"Content-Type\"]=t.headers[\"Content-Type\"]||\"application/json\",t.method=\"POST\",t.url=e,sC.request(t).then((e=>{\"string\"==typeof e.data?lC+=$T(e.data):e.data instanceof ArrayBuffer||e.data instanceof Uint8Array?lC+=e.data.byteLength:lC+=$T(JSON.stringify(e.data)),n&&r({data:e.data,headers:e.headers}),r(e.data)})).catch((e=>{sC.isCancel(e)?s(new Kg(Hg.OPERATION_ABORTED,\"cancel token canceled\")):\"ECONNABORTED\"===e.code?s(new Kg(Hg.NETWORK_TIMEOUT,e.message)):e.response?s(new Kg(Hg.NETWORK_RESPONSE_ERROR,e.response.status)):s(new Kg(Hg.NETWORK_ERROR,e.message))}))}))}async function hC(e,t){const i=new Blob([t.data],{type:\"buffer\"});return await uC(e,aC(aC({},t),{},{data:i,headers:{\"Content-Type\":\"application/octet-stream\"}}),!0)}const pC=()=>\"HTTPS\"===(cC||cC||(cC=(window.location.protocol.split(\":\")[0]||\"\").toUpperCase(),cC)),_C=()=>void 0!==window.isSecureContext;const EC=function(e){if(e.match(/[0-9]+\\.[0-9]+\\.[0-9]+$/))return e;const t=e.match(/([0-9]+\\.[0-9]+\\.[0-9]+)\\-alpha\\.([0-9]+)/);if(t&&t[1]&&t[2]){const e=t[1],i=t[2];return\"\".concat(e,\".\").concat(i)}const i=e.match(/([0-9]+\\.[0-9]+\\.[0-9]+)\\-special\\.([0-9]+)/);if(i&&i[1]&&i[2]){const e=i[1],t=i[2];return\"\".concat(e,\".\").concat(100*(Number(t)+1))}return\"4.0.0.999\"}(\"4.20.2\"),mC=function(){try{return!0===JSON.parse(\"true\")}catch(e){return!0}}();var fC;!function(e){e.Default=\"default\",e.Auto=\"auto\",e.Relay=\"relay\",e.SdRtn=\"sd-rtn\"}(fC||(fC={}));const gC=\"v4.20.2-0-g8ae7fdad(3/20/2024, 4:48:46 PM)\",TC={PROCESS_ID:\"\",ENCRYPT_AES:!0,AREAS:[\"CHINA\",\"GLOBAL\"],WEBCS_DOMAIN:[\"webrtc2-ap-web-1.agora.io\",\"webrtc2-2.ap.sd-rtn.com\"],WEBCS_DOMAIN_BACKUP_LIST:[\"webrtc2-ap-web-3.agora.io\",\"webrtc2-4.ap.sd-rtn.com\"],PROXY_CS:[\"ap-proxy-1.agora.io\",\"ap-proxy-2.agora.io\"],CDS_AP:[\"cds-ap-web-1.agora.io\",\"cds-web-2.ap.sd-rtn.com\",\"cds-ap-web-3.agora.io\",\"cds-web-4.ap.sd-rtn.com\"],ACCOUNT_REGISTER:[\"sua-ap-web-1.agora.io\",\"sua-web-2.ap.sd-rtn.com\",\"sua-ap-web-3.agora.io\",\"sua-web-4.ap.sd-rtn.com\"],UAP_AP:[\"uap-ap-web-1.agora.io\",\"uap-web-2.ap.sd-rtn.com\",\"uap-ap-web-3.agora.io\",\"uap-web-4.ap.sd-rtn.com\"],LOG_UPLOAD_SERVER:\"logservice.agora.io\",EVENT_REPORT_DOMAIN:\"statscollector-1.agora.io\",EVENT_REPORT_BACKUP_DOMAIN:\"web-2.statscollector.sd-rtn.com\",ENABLE_EVENT_REPORT:!0,GATEWAY_ADDRESS:[],GATEWAY_WSS_ADDRESS:\"\",LIVE_STREAMING_ADDRESS:\"\",HTTP_CONNECT_TIMEOUT:5e3,SIGNAL_REQUEST_TIMEOUT:1e4,REPORT_STATS:!0,UPLOAD_LOG:!1,NOT_REPORT_EVENT:[],SUBSCRIBE_TWCC:!1,PUBLISH_TWCC:!1,PING_PONG_TIME_OUT:10,WEBSOCKET_TIMEOUT_MIN:1e4,EVENT_REPORT_SEND_INTERVAL:3e3,CONFIG_DISTRIBUTE_INTERVAL:3e5,ENABLE_CONFIG_DISTRIBUTE:!0,CANDIDATE_TIMEOUT:5e3,SHOW_REPORT_INVOKER_LOG:!1,JOIN_EXTEND:\"\",PUB_EXTEND:\"\",SUB_EXTEND:\"\",FORCE_TURN:!1,TURN_ENABLE_TCP:!0,TURN_ENABLE_UDP:!0,MAX_UPLOAD_CACHE:50,UPLOAD_CACHE_INTERVAL:2e3,AJAX_REQUEST_CONCURRENT:3,REPORT_APP_SCENARIO:void 0,GATEWAY_DOMAINS:[\"edge.agora.io\",\"edge.sd-rtn.com\"],CONNECT_GATEWAY_WITHOUT_DOMAIN:!1,WORKER_DOMAIN:\"edge.agora.io\",TURN_DOMAIN:\"edge.agora.io\",EVENT_REPORT_RETRY:!0,CHROME_FORCE_PLAN_B:!1,AUDIO_SOURCE_VOLUME_UPDATE_INTERVAL:400,AUDIO_SOURCE_AVG_VOLUME_DURATION:3e3,AUDIO_VOLUME_INDICATION_INTERVAL:2e3,VOLUME_VOICE_WEIGHT:10,GET_VOLUME_OF_MUTED_AUDIO_TRACK:!1,STATS_UPDATE_INTERVAL:250,NORMAL_EVENT_QUEUE_CAPACITY:100,CUSTOM_REPORT:!0,CUSTOM_REPORT_LIMIT:20,PROXY_SERVER_TYPE2:\"webnginx-proxy.agora.io\",PROXY_SERVER_TYPE3:[\"webrtc-cloud-proxy.sd-rtn.com\",\"webrtc-cloud-proxy.agora.io\"],CUSTOM_PUB_ANSWER_MODIFIER:null,CUSTOM_SUB_ANSWER_MODIFIER:null,CUSTOM_PUB_OFFER_MODIFIER:null,CUSTOM_SUB_OFFER_MODIFIER:null,DSCP_TYPE:\"high\",REMOVE_NEW_CODECS:!0,FRAGEMENT_LENGTH:3,WEBSOCKET_COMPRESS:!1,SIMULCAST:!1,PRELOAD_MEDIA_COUNT:0,USE_PUB_RTX:!1,USE_SUB_RTX:!1,CHECK_VIDEO_VISIBLE_INTERVAL:3e4,CHECK_LOCAL_STATS_INTERVAL:100,PROFILE_SWITCH_INTERVAL:2e3,UNSUPPORTED_VIDEO_CODEC:[],ENUMERATE_DEVICES_INTERVAL:!1,ENUMERATE_DEVICES_INTERVAL_TIME:1e4,USE_NEW_TOKEN:!1,CLOSE_AFB_FOR_LOCAL_AP:!0,JOIN_MAX_CONCURRENCY:6,JOIN_WITH_FALLBACK_SIGNAL_PROXY:!0,JOIN_WITH_FALLBACK_MEDIA_PROXY:!0,JOIN_WITH_FALLBACK_MEDIA_PROXY_FORCE:!1,JOIN_GATEWAY_TRY_443PORT_DURATION:2e3,JOIN_GATEWAY_USE_443PORT_ONLY:!1,JOIN_GATEWAY_USE_DUAL_DOMAIN:!0,JOIN_GATEWAY_FALLBACK_PORT:443,USE_TURN_SERVER_OF_GATEWAY:!1,H264_PROFILE_LEVEL_ID:\"\",USE_NEW_LOG:!1,LOG_VERSION:3,MEDIA_DEVICE_CONSTRAINTS:null,ENCRYPT_PROXY_USERNAME_AND_PSW:!0,SDP_LOGGING:!1,CSP_DETECTED_HOSTNAME_LIST:[\"agora.io\",\"sd-rtn.com\"],REMOTE_AUDIO_TRACK_USES_WEB_AUDIO:!1,LOCAL_AUDIO_TRACK_USES_WEB_AUDIO:!1,BITRATE_ADAPTER_TYPE:\"STANDARD_BITRATE\",AI_DENOISER_PARAMETERS:{excludedLinks:[]},ADJUST_3A_FROM_PLUGINS:!0,RAISE_H264_BASELINE_PRIORITY:!0,FILTER_SEND_H264_BASELINE:!1,ENABLE_PUBLISHED_USER_LIST:!0,MAX_SUBSCRIPTION:50,X_GOOGLE_START_BITRATE:void 0,NEW_REPORT_SERVER:!1,NEW_REPORT_SERVER_DOMAINS:[\"data-reporting.agora.io\",\"data-reporting.agora.io\"],VIDEO_INSPECT_WORKER_MESSAGE_LENGTH_LIMIT:3e5,VIDEO_INSPECT_INTERVAL_MINIMUM:1e3,VIDEO_INSPECT_QUALITY_RATIO:.9,VIDEO_INSPECT_WORKER_MANAGER_HOST:\"edge.agora.io\",VIDEO_INSPECT_WORKER_MANAGER_PORT:\"\",VIDEO_INSPECT_WORKER_PORT:\"\",SHOW_VIDEO_INSPECT_WORKER_MESSAGE:!1,STATS_COLLECTOR_PORT:443,FORCE_TURN_TCP:!1,SUBSCRIBE_AUDIO_FILTER_TOPN:void 0,ENABLE_PUBLISH_AUDIO_FILTER:void 0,DISABLE_FEC:void 0,WEBAUDIO_INIT_OPTIONS:void 0,FILTER_VIDEO_FEC:!0,FILTER_AUDIO_FEC:!1,CHROME_DUAL_STREAM_USE_ENCODING:!0,DISABLE_DUAL_STREAM_USE_ENCODING:!1,EXTENSION_USAGE_UPLOAD_INTERVAL:1e4,ICE_RESTART:!0,ICE_RESTART_INTERVAL:1e4,NEW_ICE_RESTART:!1,ENABLE_USER_LICENSE_CHECK:!0,SIGNAL_CHANNEL:0,TRANSMITTER_INITIAL_RTT:30,TRANSMITTER_INITIAL_RTO:30,TRANSMITTER_MAX_BATCH_ACK_COUNT:2,TRANSMITTER_MAX_RTO:500,DATACHANNEL_COMPRESS:!1,FINGERPRINT:null,DC_JOIN_WITH_FAILBACK:5e3,ENABLE_VIDEO_FRAME_CALLBACK:!0,VIDEO_FREEZE_DURATION:500,SPATIALIZER_PARAMETERS:{},UPLOAD_LOG_INTERVAL:3e3,UPLOAD_LOG_REQUEST_RETRY_INTERVAL:2e3,UPLOAD_LOG_REQUEST_MAX_RETRY_INTERVAL:2e4,UPLOAD_LOG_TRY_INTERVAL_WHILE_OFF:5e3,UPLOAD_LOG_RETRY_INTERVAL_V1:1e4,UPLOAD_LOG_TWICE_RETRY_INTERVAL_V1:200,UPLOAD_LOG_LENGTH_EACH_TIME:10,APP_TYPE:0,DISABLE_WEBAUDIO:!1,CHANNEL_MEDIA_RELAY_SERVERS:void 0,KEEP_LAST_FRAME:!0,FORWARD_P2P_CREATION:!0,SYNC_GROUP:!0,BLOCK_LOCAL_CLIENT:!1,AP_AREA:!0,SVC:[],ENABLE_ENCODED_TRANSFORM:!1,ENABLE_VIDEO_SEI:!1,IMAGE_MODERATION_WORKER_HOST:\"edge.agora.io\",IMAGE_MODERATION_WORKER_MESSAGE_LENGTH_LIMIT:3e5,IMAGE_MODERATION_INTERVAL_MINIMUM:1e3,SHOW_IMAGE_MODERATION_WORKER_MESSAGE:!1,IMAGE_MODERATION_QUALITY_RATIO:.9,IMAGE_MODERATION_UPLOAD_REPORT_INTERVAL:5e3,SHOW_GLOBAL_CLIENT_LIST:!1,ENABLE_DATASTREAM_2:!1,DATASTREAM_MAX_RETRANSMITS:10,ENABLE_USER_AUTO_REBALANCE_CHECK:!0,ENABLE_INSTANT_VIDEO:!1,ENABLE_NTP_REPORT:!1,USE_XR:!1,TCP_CANDIDATE_ONLY:!1,EXTERNAL_SIGNAL_REQUEST_TIMEOUT:3e3,SHOW_P2P_LOG:!1,MAX_P2P_TIMEOUT:3e4,P2P_TOKEN_INTERVAL:1e3,SHOW_DATASTREAM2_LOG:!1,RESTRICTION_SET_PLAYBACK_DEVICE:!0,USE_PURE_ENCRYPTION_MASTER_KEY:!1,ACCOUNT_REGISTER_RETRY_TIMEOUT:1,ACCOUNT_REGISTER_RETRY_RATIO:2,ACCOUNT_REGISTER_RETRY_TIMEOUT_MAX:6e4,ACCOUNT_REGISTER_RETRY_COUNT_MAX:1e5,AUDIO_CONTEXT:null,WEBCS_BACKUP_CONNECT_TIMEOUT:6e3,PLAYER_STATE_DEFER:2e3,SIGNAL_REQUEST_WATCH_INTERVAL:1e3,FILEPATH_LENMAX:255,DUALSTREAM_OPERATION_CHECK:!0,MEDIA_ELEMENT_EXISTS_DEPTH:3,SHIM_CANDIDATE:!1,LEAVE_MSG_TIMEOUT:2e3,STATS_FILTER:{transportId:!0,googTrackId:!0},FILTER_VIDEO_CODEC:[],PLUGIN_INFO:[]};function SC(e,t,i){var n,r;bn(n=Object.keys(TC)).call(n,e)&&(!i&&bn(r=Object.keys(CC)).call(r,e)||(TC[e]=t,\"ENABLE_VIDEO_SEI\"===e&&!0===t&&(TC.ENABLE_ENCODED_TRANSFORM=!0)))}function RC(e){return TC[e]}const CC={};function IC(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function vC(e){for(var t=1;te.trackId===t.metric.trackId));return-1!==n?(i[n]=vC(vC({},i[n]),t.metric),vC(vC({},e),{},{keyMetrics:vC(vC({},e.keyMetrics),{},{publish:[...i]})})):vC(vC({},e),{},{keyMetrics:vC(vC({},e.keyMetrics),{},{publish:[...e.keyMetrics.publish,t.metric]})})}case yC.KEY_METRIC_SUBSCRIBE:{const i=e.keyMetrics.subscribe,n=i.findIndex((e=>e.userId===t.metric.userId&&e.type===t.metric.type));return-1!==n?(i[n]=vC(vC({},i[n]),t.metric),vC(vC({},e),{},{keyMetrics:vC(vC({},e.keyMetrics),{},{subscribe:[...i]})})):vC(vC({},e),{},{keyMetrics:vC(vC({},e.keyMetrics),{},{subscribe:[...e.keyMetrics.subscribe,t.metric]})})}case yC.SET_CLOUD_PROXY_SERVER_MODE:return e.cloudProxyServerMode=t.mode,e;case yC.RECORD_JOIN_CHANNEL_SERVICE:return\"number\"!=typeof t.index?e.joinChannelServiceRecords=[...e.joinChannelServiceRecords,t.record]:(e.joinChannelServiceRecords[t.index]=vC(vC({},e.joinChannelServiceRecords[t.index]),t.record),e.joinChannelServiceRecords=[...e.joinChannelServiceRecords]),e;case yC.RESET_JOIN_CHANNEL_SERVICE_RECORDS:return e.joinChannelServiceRecords=[],e;case yC.RESET_KEY_METRICS:return e.keyMetrics={publish:[],subscribe:[]},e;case yC.SET_USE_DATACHANNEL:return vC(vC({},e),{},{useDataChannel:t.val});case yC.SET_USE_P2P:return vC(vC({},e),{},{useP2P:t.val});case yC.SET_TRANSPORT_TYPE:return vC(vC({},e),{},{p2pTransport:t.val});default:return e}}(this.state,e)}set sessionId(e){this.dispatch({type:yC.SET_SESSION_ID,sessionId:e})}get sessionId(){return this.state.sessionId}set codec(e){this.state.codec=e}get codec(){return this.state.codec}get mode(){return this.state.mode}get audioCodec(){return this.state.audioCodec}get clientId(){return this.state.clientId}set p2pId(e){this.dispatch({type:yC.SET_P2P_ID,p2pId:e})}get p2pId(){return this.state.p2pId}set dcId(e){this.dispatch({type:yC.SET_DC_ID,dcId:e})}get dcId(){return this.state.dcId}set uid(e){this.dispatch({type:yC.SET_UID,uid:e})}get uid(){return this.state.uid}set intUid(e){this.dispatch({type:yC.SET_INT_UID,intUid:e})}get intUid(){return this.state.intUid}set pubId(e){this.dispatch({type:yC.SET_PUB_ID,pubId:e})}get pubId(){return this.state.pubId}set cloudProxyServerMode(e){this.dispatch({type:yC.SET_CLOUD_PROXY_SERVER_MODE,mode:e})}get cloudProxyServerMode(){return this.state.cloudProxyServerMode}set useDataChannel(e){this.dispatch({type:yC.SET_USE_DATACHANNEL,val:e})}get useDataChannel(){return this.state.useDataChannel}set useP2P(e){this.dispatch({type:yC.SET_USE_P2P,val:e})}get useP2P(){return this.state.useP2P}set p2pTransport(e){this.dispatch({type:yC.SET_TRANSPORT_TYPE,val:e})}get p2pTransport(){return this.state.p2pTransport}clientCreated(){this.dispatch({type:yC.KEY_METRIC_CLIENT_CREATED,metric:Date.now()})}joinStart(){this.dispatch({type:yC.KEY_METRIC_JOIN_START,metric:Date.now()})}joinEnd(){this.dispatch({type:yC.KEY_METRIC_JOIN_END,metric:Date.now()})}requestAPStart(){this.dispatch({type:yC.KEY_METRIC_REQUEST_AP_START,metric:Date.now()})}requestAPEnd(){this.dispatch({type:yC.KEY_METRIC_REQUEST_AP_END,metric:Date.now()})}joinGatewayStart(){this.dispatch({type:yC.KEY_METRIC_JOIN_GATEWAY_START,metric:Date.now()})}joinGatewayEnd(){this.dispatch({type:yC.KEY_METRIC_JOIN_GATEWAY_END,metric:Date.now()})}peerConnectionStart(){this.dispatch({type:yC.KEY_METRIC_PEER_CONNECTION_START,metric:Date.now()})}peerConnectionEnd(){this.dispatch({type:yC.KEY_METRIC_PEER_CONNECTION_END,metric:Date.now()})}descriptionStart(){this.dispatch({type:yC.KEY_METRIC_DESCRIPTION_START,metric:Date.now()})}signalChannelOpen(){this.dispatch({type:yC.KEY_METRIC_SIGNAL_CHANNEL_OPEN,metric:Date.now()})}iceConnectionEnd(){this.dispatch({type:yC.KEY_METRIC_ICE_CONNECTION_END,metric:Date.now()})}publish(e,t,i,n){this.dispatch({type:yC.KEY_METRIC_PUBLISH,metric:vC(vC({trackId:e,type:t},i&&{publishStart:i}),n&&{publishEnd:n})})}subscribe(e,t,i,n,r,s,o){this.dispatch({type:yC.KEY_METRIC_SUBSCRIBE,metric:vC(vC(vC(vC(vC({userId:e,type:t},i&&{subscribeStart:i}),n&&{subscribeEnd:n}),r&&{firstFrame:r}),s&&{streamAdded:s}),o&&{firstDecoded:o})})}massSubscribe(e,t,i,n){e.forEach((e=>{this.dispatch({type:yC.KEY_METRIC_SUBSCRIBE,metric:vC(vC(vC({userId:e.userId,type:e.type},t&&{subscribeStart:t}),i&&{subscribeEnd:i}),n&&{firstFrame:n})})}))}get keyMetrics(){return this.state.keyMetrics}recordJoinChannelService(e,t){\"gateway\"===e.service&&Array.isArray(e.urls)&&(e.urls=e.urls.map((e=>e.replace(/(\\d+)-\\d+-\\d+-(\\d+)/,\"$1-*-*-$2\"))));try{return\"number\"!=typeof t?(this.dispatch({type:yC.RECORD_JOIN_CHANNEL_SERVICE,record:vC(vC({},e),{},{sessionId:this.sessionId,cloudProxyMode:this.cloudProxyServerMode,uid:this.uid})}),this.state.joinChannelServiceRecords.length-1):(t<0||t>=this.state.joinChannelServiceRecords.length||this.dispatch({type:yC.RECORD_JOIN_CHANNEL_SERVICE,record:e,index:t}),t)}catch(e){return 0}}resetJoinChannelServiceRecords(){this.dispatch({type:yC.RESET_JOIN_CHANNEL_SERVICE_RECORDS})}resetKeyMetrics(){this.dispatch({type:yC.RESET_KEY_METRICS})}get joinChannelServiceRecords(){try{return this.state.joinChannelServiceRecords}catch(e){return[]}}get avoidJoinStart(){return this.state.avoidJoinStart}set avoidJoinStart(e){this.dispatch({type:yC.AVOID_JOIN_START,avoidJoinStart:e})}}var bC,wC;!function(e){e.h264=\"h264\",e.h265=\"h265\",e.vp8=\"vp8\",e.vp9=\"vp9\",e.av1=\"av1\"}(bC||(bC={})),function(e){e.opus=\"opus\",e.pcma=\"pcma\",e.pcmu=\"pcmu\",e.g722=\"g722\"}(wC||(wC={}));const OC=128,NC=96,DC=1e3,PC=10;let LC=0;const kC=new class extends dT{reportLogUploadError(e){this.emit(\"REPORT_LOG_UPLOAD\",e)}};class MC{constructor(e){sh(this,\"logger\",void 0),sh(this,\"prefixLists\",[]),this.logger=e}debug(){for(var e=arguments.length,t=new Array(e),i=0;i{for(const t in VC)if(Object.prototype.hasOwnProperty.call(VC,t)&&VC[t]===e)return t;return\"DEFAULT\"};const jC=new class{constructor(){sh(this,\"proxyServerURL\",void 0),sh(this,\"logLevel\",VC.DEBUG),sh(this,\"uploadState\",\"collecting\"),sh(this,\"uploadLogWaitingList\",[]),sh(this,\"uploadLogUploadingList\",[]),sh(this,\"uploadErrorCount\",0),sh(this,\"currentLogID\",0),sh(this,\"url\",void 0),sh(this,\"extLog\",((e,t)=>{this.appendLogToWaitingList(e,...t)}))}debug(){for(var e=arguments.length,t=new Array(e),i=0;i{this.log(...t)}),Date.now()-FC);const n=Math.max(0,Math.min(4,t[0]));if(t[0]=UC()+\" Agora-SDK [\".concat(BC(n),\"]:\"),this.appendLogToWaitingList(n,...t),n{this.uploadLog(...t)}),Date.now()-FC);const n=Math.max(0,Math.min(4,t[0]));t[0]=UC()+\" Agora-SDK [\".concat(BC(n),\"]:\"),this.appendLogToWaitingList(n,...t)}appendLogToWaitingList(e){if(!RC(\"UPLOAD_LOG\"))return;for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n{\"object\"==typeof e&&(e=JSON.stringify(e)),r+=\"\".concat(e,\" \")})),this.uploadLogWaitingList.push({payload_str:r,log_level:e,log_item_id:this.currentLogID++}),\"uploading\"===this.uploadState&&0===this.uploadLogUploadingList.length&&this.uploadLogInterval()}startUpload(){this.uploadState=\"uploading\",0===this.uploadLogUploadingList.length&&this.uploadLogInterval()}async uploadLogs(){const e=this.uploadLogUploadingList,t={sdk_version:EC,process_id:RC(\"PROCESS_ID\"),payload:JSON.stringify(e)};return fS((async()=>{const e=await sC.post(this.url||(this.proxyServerURL?\"https://\".concat(this.proxyServerURL,\"/ls/?h=\").concat(RC(\"LOG_UPLOAD_SERVER\"),\"&p=443&d=upload/v1\"):\"https://\".concat(RC(\"LOG_UPLOAD_SERVER\"),\"/upload/v1\")),t,{responseType:\"text\"});if(\"OK\"!==e.data){const t=new Error(\"unexpected upload log response\");throw t.response=e,t}}),(()=>(this.uploadLogUploadingList=[],!1)),(e=>(e.response?kC.reportLogUploadError({status:e.response.status,data:e.response.data,headers:e.response.headers,message:e.message}):e.request?kC.reportLogUploadError({status:e.request.status,message:e.message}):kC.reportLogUploadError({status:-1,message:e.message}),!0)),{timeout:RC(\"UPLOAD_LOG_REQUEST_RETRY_INTERVAL\"),maxRetryTimeout:RC(\"UPLOAD_LOG_REQUEST_MAX_RETRY_INTERVAL\")})}uploadLogInterval(){0===this.uploadLogUploadingList.length&&0===this.uploadLogWaitingList.length||(0===this.uploadLogUploadingList.length&&(this.uploadLogUploadingList=this.uploadLogWaitingList.splice(0,RC(\"UPLOAD_LOG_LENGTH_EACH_TIME\"))),this.uploadLogs().then((()=>{this.uploadErrorCount=0,this.uploadLogWaitingList.length>0&&window.setTimeout((()=>this.uploadLogInterval()),RC(\"UPLOAD_LOG_INTERVAL\"))})).catch((e=>{this.uploadErrorCount+=1,this.uploadErrorCount<2?window.setTimeout((()=>this.uploadLogInterval()),RC(\"UPLOAD_LOG_TWICE_RETRY_INTERVAL_V1\")):window.setTimeout((()=>this.uploadLogInterval()),RC(\"UPLOAD_LOG_RETRY_INTERVAL_V1\"))})))}};var GC,WC;function HC(e){return Xg(e.reportId,\"params.reportId\",0,100,!1),Xg(e.category,\"params.category\",0,100,!1),Xg(e.event,\"params.event\",0,100,!1),Xg(e.label,\"params.label\",0,100,!1),zg(e.value,\"params.value\",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,!1),!0}!function(e){e.FREE=\"free\",e.UPLOADING=\"uploading\"}(GC||(GC={})),function(e){e[e.MISC=0]=\"MISC\",e[e.INTERNAL_EVENT=1]=\"INTERNAL_EVENT\",e[e.PUBLIC_EVENT=2]=\"PUBLIC_EVENT\",e[e.WEB_EVENT=3]=\"WEB_EVENT\",e[e.INTERNAL_API=4]=\"INTERNAL_API\",e[e.WEB_API=5]=\"WEB_API\",e[e.PUBLIC_API=6]=\"PUBLIC_API\"}(WC||(WC={}));const KC={sid:\"\",lts:0,success:null,cname:null,uid:null,peer:null,cid:null,elapse:null,extend:null,vid:0};var YC,qC,zC,JC;function XC(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function QC(e){for(var t=1;t{for(const t of e){const e=QC(QC({},t),{},{sid:null,invokeId:++this.apiInvokeCount,tag:pT.TRACER});this.sendApiInvoke(e)}})),this.eventUploadTimer=window.setInterval(this.doSend.bind(this),RC(\"EVENT_REPORT_SEND_INTERVAL\")),this.setSessionIdTimer=window.setInterval(this.appendSessionId.bind(this),RC(\"EVENT_REPORT_SEND_INTERVAL\"))}getBaseInfoBySessionId(e){return this.baseInfoMap.get(e)}adjustSessionStartTime(e){if(!this.baseInfoMap.has(e)&&!this.baseInfoMap.get(e))return void jC.error(\"adjust session \".concat(e,\" start time, sid is not exist or info is undefined\"));const t=this.baseInfoMap.get(e),i=Date.now(),n=t.startTime;t.startTime=i,jC.debug(\"rewrite session \".concat(e,\" startTime: \").concat(i,\" , \").concat(i-n,\"ms\")),this.baseInfoMap.set(e,t)}setAppId(e){this._appId=e}reportApiInvoke(e,t,i){t.timeout=t.timeout||6e4,t.reportResult=void 0===t.reportResult||t.reportResult;const n=Date.now();this.apiInvokeCount+=1;const r=this.apiInvokeCount,s=()=>({tag:t.tag,invokeId:r,sid:e,name:t.name,apiInvokeTime:n,options:t.options,states:t.states||null}),o=!!RC(\"SHOW_REPORT_INVOKER_LOG\");o&&jC.info(\"\".concat(t.name,\" start\"),t.options);let a=!1;iS(t.timeout).then((()=>{a||(this.sendApiInvoke(QC(QC({},s()),{},{error:Hg.API_INVOKE_TIMEOUT,success:!1})),jC.debug(\"\".concat(t.name,\" timeout\")))}));const c=new Kg(Hg.UNEXPECTED_ERROR,\"\".concat(t.name,\": this api invoke is end\"));return{onSuccess:e=>{const n=()=>{if(a)throw c;return a=!0,this.sendApiInvoke(QC(QC({},s()),{},{success:!0},t.reportResult&&{result:e})),o&&jC.info(\"\".concat(t.name,\" onSuccess\")),e};return i?aS(n,t.name+\"Success\",i,(()=>a=!0)):n()},onError:e=>{const n=()=>{if(a)throw e;a=!0,this.sendApiInvoke(QC(QC({},s()),{},{success:!1,error:e})),o&&jC.info(\"\".concat(t.name,\" onFailure\"),e.toString())};return i?aS(n,t.name+\"Error\",i,(()=>a=!0)):n()}}}sessionInit(e,t){if(this.baseInfoMap.has(e))return;const i=Date.now(),n=this.createBaseInfo(e,i);n.cname=t.cname;const r=Object.assign({},{willUploadConsoleLog:RC(\"UPLOAD_LOG\"),maxTouchPoints:navigator.maxTouchPoints,areaVersion:mC?\"global\":\"oversea\",areas:RC(\"AREAS\")&&RC(\"AREAS\").join(\",\")},t.extend),{stringUid:s,channelProfile:o,channelMode:a,isABTestSuccess:c,lsid:d,clientRole:l}=t,u=Date.now(),h=QC(QC({},n),{},{eventType:YC.SESSION_INIT,appid:t.appid,browser:navigator.userAgent,build:gC,lts:u,elapse:u-i,extend:JSON.stringify(r),mode:t.mode,process:RC(\"PROCESS_ID\"),appType:RC(\"APP_TYPE\"),success:!0,version:EC,stringUid:s,channelProfile:o,channelMode:a,isABTestSuccess:c,lsid:d,clientType:20,clientRole:l,serviceId:RC(\"PROCESS_ID\"),extensionID:RC(\"PLUGIN_INFO\").join(\",\")||\"\"});this.send({type:qC.SESSION,data:h},!0)}joinChooseServer(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=QC(QC({},n),{},{eventType:YC.JOIN_CHOOSE_SERVER,lts:r,eventElapse:r-t.lts,chooseServerAddr:t.csAddr,errorCode:t.ec,elapse:r-i.startTime,success:t.succ,chooseServerAddrList:JSON.stringify(t.serverList),uid:t.uid?parseInt(t.uid):null,cid:t.cid?parseInt(t.cid):null,chooseServerIp:t.csIp||\"\",opid:t.opid,unilbsServerIds:t.unilbsServerIds,extend:t.extend||void 0,isHttp3:t.isHttp3});this.send({type:qC.JOIN_CHOOSE_SERVER,data:s},!0)}reqUserAccount(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=QC(QC({},n),{},{eventType:YC.REQ_USER_ACCOUNT,lts:r,success:t.success,serverAddress:t.serverAddr,stringUid:t.stringUid,uid:t.uid,errorCode:t.errorCode,elapse:r-i.startTime,eventElapse:r-t.lts,extend:JSON.stringify(t.extend)});this.send({type:qC.REQ_USER_ACCOUNT,data:s},!0)}joinGateway(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info;t.vid&&(n.vid=t.vid),n.uid=t.uid,n.cid=t.cid;const r=Date.now(),{firstSuccess:s,avoidJoinStartTime:o,isProxy:a,addr:c}=t,d=r-(s&&o?o:i.startTime),l=QC(QC({},n),{},{eventType:YC.JOIN_GATEWAY,lts:r,gatewayAddr:t.addr,success:t.succ,errorCode:t.ec,elapse:d,eventElapse:r-t.lts,firstSuccess:s,signalChannel:t.signalChannel}),u=l.success?1:0;if(t.succ&&(i.lastJoinSuccessTime=r),s)this.send({type:qC.JOIN_GATEWAY,data:l},!0);else{let e;if(c)if(a){const t=c.match(/h=(\\d{1,3}-){3}\\d{1,3}/g),i=c.match(/p=[0-9]{1,6}/g);e={isSuccess:u,gatewayIp:t&&t.length?t[0].split(\"=\")[1].replace(/-/g,\".\"):\"\",port:i&&i.length?i[0].split(\"=\")[1]:\"\",isProxy:a?1:0}}else{const t=c.match(/wss:\\/\\/(\\d{1,3}-){3}\\d{1,3}/g),i=c.match(/(:|p=)[0-9]{1,6}/g);e={isSuccess:u,gatewayIp:t&&t.length?t[0].split(\"//\")[1].replace(/-/g,\".\"):\"\",port:i&&i.length?i[0].split(/:|p=/g)[1]:\"\",isProxy:a?1:0}}else e={isSuccess:u,gatewayIp:\"\",port:\"\",isProxy:a?1:0};delete l.success,delete l.eventType,delete l.firstSuccess,l.vid=Number(l.vid);const t=Object.assign({},l,e,{eventType:YC.REJOIN_GATEWAY});this.send({type:qC.RE_JOIN_GATEWAY,data:t},!0)}}joinChannelTimeout(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=Date.now(),r=QC(QC({},i.info),{},{lts:n,timeout:t,elapse:n-i.startTime});this.send({type:qC.JOIN_CHANNEL_TIMEOUT,data:r},!0)}publish(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=QC(QC({},n),{},{eventType:YC.PUBLISH,lts:r,eventElapse:t.eventElapse,elapse:r-i.startTime,success:t.succ,errorCode:t.ec,videoName:t.videoName,audioName:t.audioName,screenName:t.screenName,screenshare:t.screenshare,audio:t.audio,video:t.video,p2pid:t.p2pid,publishRequestid:t.publishRequestid});this.send({type:qC.PUBLISH,data:s},!0)}subscribe(e,t,i){const n=this.baseInfoMap.get(e);if(!n)return;const r=n.info,s=Date.now(),o=QC(QC({},r),{},{eventType:YC.SUBSCRIBE,lts:s,eventElapse:t.eventElapse,elapse:s-n.startTime,success:t.succ,errorCode:t.ec,video:t.video,audio:t.audio,subscribeRequestid:t.subscribeRequestid,p2pid:t.p2pid},i&&{extend:JSON.stringify({isMassSubscribe:!0})});\"string\"==typeof t.peerid?o.peerSuid=t.peerid:o.peer=t.peerid,this.send({type:qC.SUBSCRIBE,data:o},!0)}wsCompressorInit(e){var t;const i=[...ph(t=this.baseInfoMap).call(t)],n=i.length?i[0]:\"UnableToGetSid\",r=this.baseInfoMap.get(n);if(!r)return;const s=r.info,o=Date.now(),a=QC(QC({},s),{},{eventType:YC.WS_COMPRESSOR_INIT,lts:o,eventElapse:e.eventElapse,elapse:o-r.startTime,status:e.status?1:2});this.send({type:qC.WS_COMPRESSOR_INIT,data:a},!0)}firstRemoteVideoDecode(e,t,i,n){const r=this.baseInfoMap.get(e);if(!r)return;const s=r.info,o=Date.now(),a=QC(QC(QC({},s),n),{},{elapse:o-r.startTime,eventType:t,lts:o,firstDecodeFrame:Math.max(o-r.startTime,0),apEnd:Math.max(n.apEnd-r.startTime,0),apStart:Math.max(n.apStart-r.startTime,0),joinGwEnd:Math.max(n.joinGwEnd-r.startTime,0),joinGwStart:Math.max(n.joinGwStart-r.startTime,0),pcEnd:Math.max(n.pcEnd-r.startTime,0),pcStart:Math.max(n.pcStart-r.startTime,0),subscriberEnd:Math.max(n.subscriberEnd-r.startTime,0),subscriberStart:Math.max(n.subscriberStart-r.startTime,0),videoAddNotify:Math.max(n.videoAddNotify-r.startTime,0)});this.send({type:i,data:a},!0)}firstRemoteFrame(e,t,i,n){const r=this.baseInfoMap.get(e);if(!r)return;const s=r.info,o=Date.now(),a=QC(QC(QC({},s),n),{},{elapse:o-r.startTime,eventType:t,lts:o});this.send({type:i,data:a},!0)}pcStats(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=QC(QC(QC({},n),t),{},{vid:void 0===n.vid?0:Number(n.vid),elapse:r-i.startTime,eventType:YC.PC_STATS,lts:r});this.send({type:qC.PC_STATS,data:s},!0)}updateRemoteRTPCapabilities(e,t){if(e){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=QC(QC(QC({},n),t),{},{vid:void 0===n.vid?0:Number(n.vid),eventType:YC.UPDATE_REMOTE_RTPCAPABILITIES,lts:r});this.send({type:qC.UPDATE_REMOTE_RTPCAPABILITIES,data:s},!0)}}onGatewayStream(e,t,i,n){const r=this.baseInfoMap.get(e);if(!r)return;const s=r.info,o=Date.now(),a=QC(QC(QC({},s),n),{},{eventType:t,lts:o});this.send({type:i,data:a},!0)}streamSwitch(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=QC(QC({},n),{},{eventType:YC.STREAM_SWITCH,lts:r,isDual:t.isdual,elapse:r-i.startTime,success:t.succ});this.send({type:qC.STREAM_SWITCH,data:s},!0)}requestProxyAppCenter(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=QC(QC({},n),{},{eventType:YC.REQUEST_PROXY_APPCENTER,lts:r,eventElapse:r-t.lts,elapse:r-i.startTime,APAddr:t.APAddr,workerManagerList:t.workerManagerList,response:t.response,errorCode:t.ec,success:t.succ});this.send({type:qC.REQUEST_PROXY_APPCENTER,data:s},!0)}requestProxyWorkerManager(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=QC(QC({},n),{},{eventType:YC.REQUEST_PROXY_WORKER_MANAGER,lts:r,eventElapse:r-t.lts,elapse:r-i.startTime,workerManagerAddr:t.workerManagerAddr,response:t.response,errorCode:t.ec,success:t.succ});this.send({type:qC.REQUEST_PROXY_WORKER_MANAGER,data:s},!0)}setProxyServer(e){this.proxyServer=e,e?jC.debug(\"reportProxyServerurl: \".concat(e)):jC.debug(\"disable reportProxyServerurl: \".concat(e))}peerPublishStatus(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=QC(QC({},n),{},{subscribeElapse:t.subscribeElapse,peer:t.peer,peerPublishDuration:Math.max(t.audioPublishDuration,t.videoPublishDuration),audiotag:t.audioPublishDuration>0?1:-1,videotag:t.videoPublishDuration>0?1:-1,lts:r,elapse:r-i.startTime,joinChannelSuccessElapse:r-(i.lastJoinSuccessTime||r),peerPublishDurationVideo:t.videoPublishDuration,peerPublishDurationAudio:t.audioPublishDuration});this.send({type:qC.PEER_PUBLISH_STATUS,data:s},!0)}workerEvent(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=function(e,t,i){const n=e[t];if(!n||\"string\"!=typeof n)return[e];e[t]=\"\";const r=$T(JSON.stringify(e));let s=0;const o=[];let a=0;for(let c=0;cthis.send({type:qC.WORKER_EVENT,data:e},!0)))}apworkerEvent(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=QC(QC(QC({},n),t),{},{elapse:r-i.startTime,lts:r});this.send({type:qC.AP_WORKER_EVENT,data:s},!0)}joinWebProxyAP(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=QC(QC(QC({},n),t),{},{elapse:r-i.startTime,lts:r,extend:t.extend||void 0});this.send({type:qC.JOIN_WEB_PROXY_AP,data:s},!0)}WebSocketQuit(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=QC(QC(QC({},n),t),{},{elapse:r-i.startTime,lts:r});this.send({type:qC.WEBSOCKET_QUIT,data:s},!0)}async sendCustomReportMessage(e,t){if(this.customReportCount+=t.length,this.customReportCount>RC(\"CUSTOM_REPORT_LIMIT\"))throw new Kg(Hg.CUSTOM_REPORT_FREQUENCY_TOO_HIGH);this.customReportCounterTimer||(this.customReportCounterTimer=window.setInterval((()=>{this.customReportCount=0}),5e3));const i=Date.now(),n=t.map((t=>({type:qC.USER_ANALYTICS,data:QC(QC({sid:e},t),{},{lts:i})})));try{RC(\"NEW_REPORT_SERVER\")?await this.postDataToStatsCollector2(n):await this.postDataToStatsCollector(n)}catch(e){throw jC.error(\"send custom report message failed\",e.toString()),new Kg(Hg.CUSTOM_REPORT_SEND_FAILED,e.message)}}sendApiInvoke(e){const t=RC(\"NOT_REPORT_EVENT\");if(e.tag&&bn(t)&&bn(t).call(t,e.tag))return!1;if(null===e.sid)return this.apiInvokeUploadPendingItems.push(e),!1;const i=this.baseInfoMap.get(e.sid);if(!i)return this.apiInvokeUploadPendingItems.push(e),!1;const{cname:n,uid:r,cid:s}=i.info;let o;if(e.lts=e.lts||Date.now(),e.error)if(e.error instanceof Kg){const{code:t,message:i}=e.error;o=t||(i||e.error.toString())}else o=e.error.toString();const a={invokeId:e.invokeId,sid:e.sid,cname:n,cid:s,uid:r,lts:e.lts,success:e.success,elapse:e.lts-i.startTime,execElapse:e.lts-e.apiInvokeTime,apiName:e.name,options:e.options?JSON.stringify(e.options):void 0,execStates:e.states?JSON.stringify(e.states):void 0,execResult:e.result?JSON.stringify(e.result):void 0,errorCode:e.error?o:void 0,errorMsg:e.error?JSON.stringify(e.error):void 0};return this.send({type:qC.API_INVOKE,data:a},!1),!0}appendSessionId(){ZC.__CLIENT_LIST__.forEach((e=>{if(e._sessionId){const t=this.apiInvokeUploadPendingItems.length;for(let i=0;iRC(\"NORMAL_EVENT_QUEUE_CAPACITY\")&&this.normalEventUploadPendingItems.splice(0,1),this.normalEventUploadPendingItems.length>=10&&this.sendItems(this.normalEventUploadPendingItems,!1)}doSend(){this.keyEventUploadPendingItems.length>0&&this.sendItems(this.keyEventUploadPendingItems,!0),this.normalEventUploadPendingItems.length>0&&Date.now()-this.lastSendNormalEventTime>=5e3&&this.sendItems(this.normalEventUploadPendingItems,!1)}sendItems(e,t){const i=[],n=[];for(;e.length;){const t=e.shift();i.length<20?i.push(t):n.push(t)}e.push(...n);for(const e of[...i]){var r;if(-1!==this.ltsList.indexOf(e.data.lts))e.data.lts=this.ltsList[this.ltsList.length-1]+1,this.ltsList.push(e.data.lts);else this.ltsList.push(e.data.lts),ep(r=this.ltsList).call(r,((e,t)=>e-t))}t||(this.lastSendNormalEventTime=Date.now());return RC(\"ENABLE_EVENT_REPORT\")?(i.length&&(RC(\"NEW_REPORT_SERVER\")?this.postDataToStatsCollector2(i):this.postDataToStatsCollector(i)).catch((e=>i=>{RC(\"EVENT_REPORT_RETRY\")&&(t?this.keyEventUploadPendingItems=this.keyEventUploadPendingItems.concat(e):(this.normalEventUploadPendingItems=this.normalEventUploadPendingItems.concat(e),this.normalEventUploadPendingItems.length>RC(\"NORMAL_EVENT_QUEUE_CAPACITY\")&&(this.normalEventUploadPendingItems.splice(0,this.normalEventUploadPendingItems.length-RC(\"NORMAL_EVENT_QUEUE_CAPACITY\")),jC.warning(\"report: drop normal events\"))))})(i)),e):e}async postDataToStatsCollector2(e){wT.networkState===gT.OFFLINE&&await cg.race([wT.onlineWaiter,iS(2*ES.maxRetryTimeout)]);const t=e=>{let t=new Uint8Array;return e.forEach((e=>{const i=sT(JSON.stringify(e.data)),n=new ArrayBuffer(5),r=(e=>{let t=0;return Object.entries(qC).forEach((i=>{let[n,r]=i;r===e.type&&(t=EventNameToID[n])})),t})(e),s=new DataView(n);s.setUint16(0,i.byteLength,!0),s.setUint8(2,255&r),s.setUint8(3,r>>>8&255),s.setUint8(4,r>>>16&255),t=oT(t,new Uint8Array(n)),t=oT(t,i)})),t},i=\"event\";let n=this.proxyServer?\"https://\".concat(this.proxyServer,\"/rs/?h=\").concat(RC(\"NEW_REPORT_SERVER_DOMAINS\")[0],\"&p=443&d=\").concat(i):\"https://\".concat(RC(\"NEW_REPORT_SERVER_DOMAINS\")[0],\"/\").concat(i);for(let r=0;r<2;r+=1){1===r&&(n=this.proxyServer?\"https://\".concat(this.proxyServer,\"/rs/?h=\").concat(RC(\"NEW_REPORT_SERVER_DOMAINS\")[1],\"&p=443&d=\").concat(i):\"https://\".concat(RC(\"NEW_REPORT_SERVER_DOMAINS\")[1],\"/\").concat(i));try{await uC(n,{timeout:1e4,data:t(e),headers:QC(QC({biz:\"webrtc\",sendts:Math.round(Date.now()/1e3),debug:\"false\"},this._appId&&{appid:this._appId}),{},{\"Content-Type\":\"application/octet-stream\"})},!0)}catch(e){if(1===r)throw e;continue}return}}async postDataToStatsCollector(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const i={msgType:\"EventMessages\",sentTs:Math.round(Date.now()/1e3),payloads:e.map((e=>JSON.stringify(e))),vid:(e=>{const t=e&&e.data.sid&&this.baseInfoMap.get(e.data.sid);return t&&t.info.vid&&+t.info.vid||0})(e[0])};wT.networkState===gT.OFFLINE&&await cg.race([wT.onlineWaiter,iS(2*ES.maxRetryTimeout)]);const n=t?\"/events/proto-raws\":\"/events/messages\";let r=this.url||(this.proxyServer?\"https://\".concat(this.proxyServer,\"/rs/?h=\").concat(RC(\"EVENT_REPORT_DOMAIN\"),\"&p=\").concat(RC(\"STATS_COLLECTOR_PORT\"),\"&d=\").concat(n):\"https://\".concat(RC(\"EVENT_REPORT_DOMAIN\"),\":\").concat(RC(\"STATS_COLLECTOR_PORT\")).concat(n));for(let e=0;e<2;e+=1){1===e&&(r=this.backupUrl||(this.proxyServer?\"https://\".concat(this.proxyServer,\"/rs/?h=\").concat(RC(\"EVENT_REPORT_BACKUP_DOMAIN\"),\"&p=\").concat(RC(\"STATS_COLLECTOR_PORT\"),\"&d=\").concat(n):\"https://\".concat(RC(\"EVENT_REPORT_BACKUP_DOMAIN\"),\":\").concat(RC(\"STATS_COLLECTOR_PORT\")).concat(n)));try{t?await hC(r,{timeout:1e4,data:i}):await uC(r,{timeout:1e4,data:i})}catch(t){if(1===e)throw t;continue}return}}createBaseInfo(e,t){const i=Object.assign({},KC);return i.sid=e,this.baseInfoMap.set(e,{info:i,startTime:t}),i}reportResourceTiming(e,t){const i=performance.getEntriesByName(e),n=i[i.length-1];n&&this.reportApiInvoke(t,{name:\"Client.resourceTiming\",options:n,tag:pT.TRACER}).onSuccess()}}function $C(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function(t,i,n){const r=n.value;if(\"function\"==typeof r){const s=e.className||t.__className__||(\"AgoraRTCClient\"===t.constructor.name?\"Client\":t.constructor.name);n.value=function(){for(var t=arguments.length,n=new Array(t),o=0;o(c.onSuccess(e.reportResult&&t),t))).catch((e=>{throw c.onError(e),e})):(c.onSuccess(e.reportResult&&t),t)}catch(e){throw c.onError(e),e}}}return n}}sh(ZC,\"__CLIENT_LIST__\",[]);const eI=new ZC;kC.on(\"REPORT_LOG_UPLOAD\",(e=>{e.networkState=wT.networkState,eI.reportApiInvoke(null,{name:\"logUploadError\",options:e,tag:pT.TRACER})}));const tI=[\"CHINA\",\"GLOBAL\"],iI=function(){const e=\"us\".concat(\"erna\",\"me\"),t=\"pa\".concat(\"sswo\",\"rd\"),i=[\"t\",\"s\",\"t\"];i.splice(1,0,\"e\");const n=i.join(\"\"),r=[];for(let e=0;e<6;e++)r.push(\"1\");const s=r.join(\"\"),o={};return o[e]=n,o[t]=s,Object.assign(o,{turnServerURL:\"\",tcpport:3433,udpport:3478,forceturn:!1})}();window.DEFAULT_TURN_CONFIG=iI,mC||(TC.WEBCS_DOMAIN=[\"ap-web-1-oversea.agora.io\",\"ap-web-1-north-america.agora.io\"],TC.WEBCS_DOMAIN_BACKUP_LIST=[\"ap-web-2-oversea.agora.io\",\"ap-web-2-north-america.agora.io\"],TC.PROXY_CS=[\"proxy-ap-web-oversea.agora.io\",\"proxy-ap-web-america.agora.io\"],TC.CDS_AP=[\"cds-ap-web-oversea.agora.io\",\"cds-ap-web-america.agora.io\",\"cds-ap-web-america2.agora.io\"],TC.ACCOUNT_REGISTER=[\"sua-ap-web-oversea.agora.io\",\"sua-ap-web-america.agora.io\",\"sua-ap-web-america2.agora.io\"],TC.UAP_AP=[\"uap-ap-web-oversea.agora.io\",\"uap-ap-web-america.agora.io\",\"uap-ap-web-america2.agora.io\"],TC.LOG_UPLOAD_SERVER=\"logservice-oversea.agora.io\",TC.EVENT_REPORT_DOMAIN=\"statscollector-1-oversea.agora.io\",TC.EVENT_REPORT_BACKUP_DOMAIN=\"statscollector-2-oversea.agora.io\",TC.PROXY_SERVER_TYPE3=\"webrtc-cloud-proxy.agora.io\",TC.AREAS=[\"NORTH_AMERICA\",\"OVERSEA\"]);const nI=[[0,1,2,3,4,5,5],[0,2,2,3,4,5,5],[0,3,3,3,4,5,5],[0,4,4,4,4,5,5],[0,5,5,5,5,5,5]],rI=[];function sI(e,t){return!!t&&rI.some((i=>i.uid===e&&i.channelName===t))}ZC.__CLIENT_LIST__=rI;var oI,aI,cI,dI,lI,uI,hI,pI,_I,EI,mI,fI,gI,TI,SI,RI,CI,II=zi(\"Array\").values,vI=ln,yI=Ze,AI=l,bI=II,wI=Array.prototype,OI={DOMTokenList:!0,NodeList:!0},NI=i((function(e){var t=e.values;return e===wI||AI(wI,e)&&t===wI.values||yI(OI,vI(e))?bI:t}));function DI(e,t,i,n){var r,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if(\"object\"==typeof Reflect&&\"function\"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,n);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(s<3?r(o):s>3?r(t,i,o):r(t,i))||o);return s>3&&o&&Object.defineProperty(t,i,o),o}function PI(e,t){if(\"object\"==typeof Reflect&&\"function\"==typeof Reflect.metadata)return Reflect.metadata(e,t)}!function(e){e.L1T1=\"L1T1\",e.L1T2=\"L1T2\",e.L1T3=\"L1T3\",e.L2T1_KEY=\"L2T1_KEY\",e.L2T2_KEY=\"L2T2_KEY\",e.L2T3_KEY=\"L2T3_KEY\",e.L3T1_KEY=\"L3T1_KEY\",e.L3T2_KEY=\"L3T2_KEY\",e.L3T3_KEY=\"L3T3_KEY\"}(oI||(oI={})),function(e){e.CERTIFICATE=\"certificate\",e.CODEC=\"codec\",e.CANDIDATE_PAIR=\"candidate-pair\",e.LOCAL_CANDIDATE=\"local-candidate\",e.REMOTE_CANDIDATE=\"remote-candidate\",e.INBOUND=\"inbound-rtp\",e.TRACK=\"track\",e.OUTBOUND=\"outbound-rtp\",e.PC=\"peer-connection\",e.REMOTE_INBOUND=\"remote-inbound-rtp\",e.REMOTE_OUTBOUND=\"remote-outbound-rtp\",e.TRANSPORT=\"transport\",e.CSRC=\"csrc\",e.DATA_CHANNEL=\"data-channel\",e.STREAM=\"stream\",e.SENDER=\"sender\",e.RECEIVER=\"receiver\"}(aI||(aI={})),function(e){e[e.ACCESS_POINT=101]=\"ACCESS_POINT\",e[e.UNILBS=201]=\"UNILBS\",e[e.STRING_UID_ALLOCATOR=901]=\"STRING_UID_ALLOCATOR\"}(cI||(cI={})),function(e){e[e.IIIEGAL_APPID=1]=\"IIIEGAL_APPID\",e[e.IIIEGAL_UID=2]=\"IIIEGAL_UID\",e[e.INTERNAL_ERROR=3]=\"INTERNAL_ERROR\"}(dI||(dI={})),function(e){e[e.INVALID_VENDOR_KEY=5]=\"INVALID_VENDOR_KEY\",e[e.INVALID_CHANNEL_NAME=7]=\"INVALID_CHANNEL_NAME\",e[e.INTERNAL_ERROR=8]=\"INTERNAL_ERROR\",e[e.NO_AUTHORIZED=9]=\"NO_AUTHORIZED\",e[e.DYNAMIC_KEY_TIMEOUT=10]=\"DYNAMIC_KEY_TIMEOUT\",e[e.NO_ACTIVE_STATUS=11]=\"NO_ACTIVE_STATUS\",e[e.DYNAMIC_KEY_EXPIRED=13]=\"DYNAMIC_KEY_EXPIRED\",e[e.STATIC_USE_DYNAMIC_KEY=14]=\"STATIC_USE_DYNAMIC_KEY\",e[e.DYNAMIC_USE_STATIC_KEY=15]=\"DYNAMIC_USE_STATIC_KEY\",e[e.USER_OVERLOAD=16]=\"USER_OVERLOAD\",e[e.FORBIDDEN_REGION=18]=\"FORBIDDEN_REGION\",e[e.CANNOT_MEET_AREA_DEMAND=19]=\"CANNOT_MEET_AREA_DEMAND\"}(lI||(lI={})),function(e){e[e.NO_FLAG_SET=100]=\"NO_FLAG_SET\",e[e.FLAG_SET_BUT_EMPTY=101]=\"FLAG_SET_BUT_EMPTY\",e[e.INVALID_FALG_SET=102]=\"INVALID_FALG_SET\",e[e.FLAG_SET_BUT_NO_RE=103]=\"FLAG_SET_BUT_NO_RE\",e[e.INVALID_SERVICE_ID=104]=\"INVALID_SERVICE_ID\",e[e.NO_SERVICE_AVAILABLE=200]=\"NO_SERVICE_AVAILABLE\",e[e.NO_SERVICE_AVAILABLE_P2P=201]=\"NO_SERVICE_AVAILABLE_P2P\",e[e.NO_SERVICE_AVAILABLE_VOICE=202]=\"NO_SERVICE_AVAILABLE_VOICE\",e[e.NO_SERVICE_AVAILABLE_WEBRTC=203]=\"NO_SERVICE_AVAILABLE_WEBRTC\",e[e.NO_SERVICE_AVAILABLE_CDS=204]=\"NO_SERVICE_AVAILABLE_CDS\",e[e.NO_SERVICE_AVAILABLE_CDN=205]=\"NO_SERVICE_AVAILABLE_CDN\",e[e.NO_SERVICE_AVAILABLE_TDS=206]=\"NO_SERVICE_AVAILABLE_TDS\",e[e.NO_SERVICE_AVAILABLE_REPORT=207]=\"NO_SERVICE_AVAILABLE_REPORT\",e[e.NO_SERVICE_AVAILABLE_APP_CENTER=208]=\"NO_SERVICE_AVAILABLE_APP_CENTER\",e[e.NO_SERVICE_AVAILABLE_ENV0=209]=\"NO_SERVICE_AVAILABLE_ENV0\",e[e.NO_SERVICE_AVAILABLE_VOET=210]=\"NO_SERVICE_AVAILABLE_VOET\",e[e.NO_SERVICE_AVAILABLE_STRING_UID=211]=\"NO_SERVICE_AVAILABLE_STRING_UID\",e[e.NO_SERVICE_AVAILABLE_WEBRTC_UNILBS=212]=\"NO_SERVICE_AVAILABLE_WEBRTC_UNILBS\",e[e.NO_SERVICE_AVAILABLE_UNILBS_FLV=213]=\"NO_SERVICE_AVAILABLE_UNILBS_FLV\"}(uI||(uI={})),function(e){e[e.K_TIMESTAMP_EXPIRED=2]=\"K_TIMESTAMP_EXPIRED\",e[e.K_CHANNEL_PERMISSION_INVALID=3]=\"K_CHANNEL_PERMISSION_INVALID\",e[e.K_CERTIFICATE_INVALID=4]=\"K_CERTIFICATE_INVALID\",e[e.K_CHANNEL_NAME_EMPTY=5]=\"K_CHANNEL_NAME_EMPTY\",e[e.K_CHANNEL_NOT_FOUND=6]=\"K_CHANNEL_NOT_FOUND\",e[e.K_TICKET_INVALID=7]=\"K_TICKET_INVALID\",e[e.K_CHANNEL_CONFLICTED=8]=\"K_CHANNEL_CONFLICTED\",e[e.K_SERVICE_NOT_READY=9]=\"K_SERVICE_NOT_READY\",e[e.K_SERVICE_TOO_HEAVY=10]=\"K_SERVICE_TOO_HEAVY\",e[e.K_UID_BANNED=14]=\"K_UID_BANNED\",e[e.K_IP_BANNED=15]=\"K_IP_BANNED\",e[e.K_CHANNEL_BANNED=16]=\"K_CHANNEL_BANNED\",e[e.K_AUTO_REBALANCE=28]=\"K_AUTO_REBALANCE\",e[e.WARN_NO_AVAILABLE_CHANNEL=103]=\"WARN_NO_AVAILABLE_CHANNEL\",e[e.WARN_LOOKUP_CHANNEL_TIMEOUT=104]=\"WARN_LOOKUP_CHANNEL_TIMEOUT\",e[e.WARN_LOOKUP_CHANNEL_REJECTED=105]=\"WARN_LOOKUP_CHANNEL_REJECTED\",e[e.WARN_OPEN_CHANNEL_TIMEOUT=106]=\"WARN_OPEN_CHANNEL_TIMEOUT\",e[e.WARN_OPEN_CHANNEL_REJECTED=107]=\"WARN_OPEN_CHANNEL_REJECTED\",e[e.WARN_REQUEST_DEFERRED=108]=\"WARN_REQUEST_DEFERRED\",e[e.ERR_DYNAMIC_KEY_TIMEOUT=109]=\"ERR_DYNAMIC_KEY_TIMEOUT\",e[e.ERR_NO_AUTHORIZED=110]=\"ERR_NO_AUTHORIZED\",e[e.ERR_VOM_SERVICE_UNAVAILABLE=111]=\"ERR_VOM_SERVICE_UNAVAILABLE\",e[e.ERR_NO_CHANNEL_AVAILABLE_CODE=112]=\"ERR_NO_CHANNEL_AVAILABLE_CODE\",e[e.ERR_MASTER_VOCS_UNAVAILABLE=114]=\"ERR_MASTER_VOCS_UNAVAILABLE\",e[e.ERR_INTERNAL_ERROR=115]=\"ERR_INTERNAL_ERROR\",e[e.ERR_NO_ACTIVE_STATUS=116]=\"ERR_NO_ACTIVE_STATUS\",e[e.ERR_INVALID_UID=117]=\"ERR_INVALID_UID\",e[e.ERR_DYNAMIC_KEY_EXPIRED=118]=\"ERR_DYNAMIC_KEY_EXPIRED\",e[e.ERR_STATIC_USE_DYANMIC_KE=119]=\"ERR_STATIC_USE_DYANMIC_KE\",e[e.ERR_DYNAMIC_USE_STATIC_KE=120]=\"ERR_DYNAMIC_USE_STATIC_KE\",e[e.ERR_NO_VOCS_AVAILABLE=2e3]=\"ERR_NO_VOCS_AVAILABLE\",e[e.ERR_NO_VOS_AVAILABLE=2001]=\"ERR_NO_VOS_AVAILABLE\",e[e.ERR_JOIN_CHANNEL_TIMEOUT=2002]=\"ERR_JOIN_CHANNEL_TIMEOUT\",e[e.ERR_REPEAT_JOIN_CHANNEL=2003]=\"ERR_REPEAT_JOIN_CHANNEL\",e[e.ERR_JOIN_BY_MULTI_IP=2004]=\"ERR_JOIN_BY_MULTI_IP\",e[e.ERR_NOT_JOINED=2011]=\"ERR_NOT_JOINED\",e[e.ERR_REPEAT_JOIN_REQUEST=2012]=\"ERR_REPEAT_JOIN_REQUEST\",e[e.ERR_INVALID_VENDOR_KEY=2013]=\"ERR_INVALID_VENDOR_KEY\",e[e.ERR_INVALID_CHANNEL_NAME=2014]=\"ERR_INVALID_CHANNEL_NAME\",e[e.ERR_INVALID_STRINGUID=2015]=\"ERR_INVALID_STRINGUID\",e[e.ERR_TOO_MANY_USERS=2016]=\"ERR_TOO_MANY_USERS\",e[e.ERR_SET_CLIENT_ROLE_TIMEOUT=2017]=\"ERR_SET_CLIENT_ROLE_TIMEOUT\",e[e.ERR_SET_CLIENT_ROLE_NO_PERMISSION=2018]=\"ERR_SET_CLIENT_ROLE_NO_PERMISSION\",e[e.ERR_SET_CLIENT_ROLE_ALREADY_IN_USE=2019]=\"ERR_SET_CLIENT_ROLE_ALREADY_IN_USE\",e[e.ERR_PUBLISH_REQUEST_INVALID=2020]=\"ERR_PUBLISH_REQUEST_INVALID\",e[e.ERR_SUBSCRIBE_REQUEST_INVALID=2021]=\"ERR_SUBSCRIBE_REQUEST_INVALID\",e[e.ERR_NOT_SUPPORTED_MESSAGE=2022]=\"ERR_NOT_SUPPORTED_MESSAGE\",e[e.ERR_ILLEAGAL_PLUGIN=2023]=\"ERR_ILLEAGAL_PLUGIN\",e[e.ERR_REJOIN_TOKEN_INVALID=2024]=\"ERR_REJOIN_TOKEN_INVALID\",e[e.ERR_REJOIN_USER_NOT_JOINED=2025]=\"ERR_REJOIN_USER_NOT_JOINED\",e[e.ERR_INVALID_OPTIONAL_INFO=2027]=\"ERR_INVALID_OPTIONAL_INFO\",e[e.ILLEGAL_AES_PASSWORD=2028]=\"ILLEGAL_AES_PASSWORD\",e[e.ILLEGAL_CLIENT_ROLE_LEVEL=2029]=\"ILLEGAL_CLIENT_ROLE_LEVEL\",e[e.ERR_TOO_MANY_BROADCASTERS=2031]=\"ERR_TOO_MANY_BROADCASTERS\",e[e.ERR_TOO_MANY_SUBSCRIBERS=2032]=\"ERR_TOO_MANY_SUBSCRIBERS\",e[e.ERR_LICENSE_MISSING=32769]=\"ERR_LICENSE_MISSING\",e[e.ERR_LICENSE_EXPIRED=32771]=\"ERR_LICENSE_EXPIRED\",e[e.ERR_LICENSE_MINUTES_EXCEEDED=32773]=\"ERR_LICENSE_MINUTES_EXCEEDED\",e[e.ERR_LICENSE_PERIOD_INVALID=32774]=\"ERR_LICENSE_PERIOD_INVALID\",e[e.ERR_LICENSE_MULTIPLE_SDK_SERVICE=32778]=\"ERR_LICENSE_MULTIPLE_SDK_SERVICE\",e[e.ERR_LICENSE_ILLEGAL=32783]=\"ERR_LICENSE_ILLEGAL\",e[e.ERR_TEST_RECOVER=9e3]=\"ERR_TEST_RECOVER\",e[e.ERR_TEST_TRYNEXT=9001]=\"ERR_TEST_TRYNEXT\",e[e.ERR_TEST_RETRY=9002]=\"ERR_TEST_RETRY\"}(hI||(hI={})),function(e){e.CONNECTING=\"connecting\",e.CONNECTED=\"connected\",e.RECONNECTING=\"reconnecting\",e.CLOSED=\"closed\"}(pI||(pI={})),function(e){e.WS_CONNECTED=\"ws_connected\",e.WS_RECONNECTING=\"ws_reconnecting\",e.WS_CLOSED=\"ws_closed\",e.WS_RECONNECT_WAITTING_FINISH=\"ws_reconnect_waitting_finish\",e.WS_RECONNECT_CREATE_CONNECTION=\"ws_reconnect_create_connection\",e.ON_BINARY_DATA=\"on_binary_data\",e.REQUEST_RECOVER=\"request_recover\",e.REQUEST_JOIN_INFO=\"request_join_info\",e.REQUEST_REJOIN_INFO=\"req_rejoin_info\",e.IS_P2P_DISCONNECTED=\"is_p2p_dis\",e.DISCONNECT_P2P=\"dis_p2p\",e.ABORT_P2P_EXECUTION=\"abort_p2p_execution\",e.NEED_RENEW_SESSION=\"need-sid\",e.REPORT_JOIN_GATEWAY=\"report_join_gateway\",e.REQUEST_TIMEOUT=\"request_timeout\",e.REQUEST_SUCCESS=\"request_success\",e.JOIN_RESPONSE=\"join_response\",e.DATACHANNEL_PRECONNECT=\"datachannel_preconnect\",e.DATACHANNEL_CONNECTING=\"datachannel_connecting\",e.DATACHANNEL_FAILBACK=\"datachannel_failback\",e.P2P_CONNECTION=\"p2p_connection\",e.P2P_REMOTE_CANDIDATE_UPDATE=\"p2p_remote_candidate_update\",e.P2P_SUBSCRIBE=\"p2p_subscribe\",e.P2P_UNSUBSCRIBE=\"p2p_unsubscribe\",e.P2P_EXCHANGE_SDP=\"p2p_exchange_sdp\",e.P2P_ON_ADD_VIDEO_STREAM=\"p2p_on_add_video_stream\",e.P2P_ON_ADD_AUDIO_STREAM=\"p2p_on_add_audio_stream\"}(_I||(_I={})),function(e){e.PING=\"ping\",e.PING_BACK=\"ping_back\",e.JOIN=\"join_v3\",e.REJOIN=\"rejoin_v3\",e.LEAVE=\"leave\",e.SET_CLIENT_ROLE=\"set_client_role\",e.PUBLISH=\"publish\",e.PUBLISH_DATASTREAM=\"publish_datastream\",e.UNPUBLISH=\"unpublish\",e.UNPUBLISH_DATASTREAM=\"unpublish_datastream\",e.SUBSCRIBE=\"subscribe\",e.PRE_SUBSCRIBE=\"pre_subscribe\",e.SUBSCRIBE_DATASTREAM=\"subscribe_datastream\",e.SUBSCRIBE_STREAMS=\"subscribe_streams\",e.UNSUBSCRIBE=\"unsubscribe\",e.UNSUBSCRIBE_DATASTREAM=\"unsubscribe_datastream\",e.UNSUBSCRIBE_STREAMS=\"unsubscribe_streams\",e.SUBSCRIBE_CHANGE=\"subscribe_change\",e.TRAFFIC_STATS=\"traffic_stats\",e.RENEW_TOKEN=\"renew_token\",e.SWITCH_VIDEO_STREAM=\"switch_video_stream\",e.DEFAULT_VIDEO_STREAM=\"default_video_stream\",e.SET_FALLBACK_OPTION=\"set_fallback_option\",e.GATEWAY_INFO=\"gateway_info\",e.CONTROL=\"control\",e.SEND_METADATA=\"send_metadata\",e.DATA_STREAM=\"data_stream\",e.PICK_SVC_LAYER=\"pick_svc_layer\",e.RESTART_ICE=\"restart_ice\",e.CONNECT_PC=\"connect_pc\",e.SET_VIDEO_PROFILE=\"set_video_profile\",e.SET_PARAMETER=\"set_parameter\",e.SET_RTM2_FLAG=\"set_rtm2_flag\"}(EI||(EI={})),function(e){e.WRTC_STATS=\"wrtc_stats\",e.WS_INFLATE_DATA_LENGTH=\"ws_inflate_data_length\",e.DENOISER_STATS=\"denoiser_stats\",e.EXTENSION_USAGE_STATS=\"extension_usage_stats\"}(mI||(mI={})),function(e){e.ON_USER_ONLINE=\"on_user_online\",e.ON_USER_OFFLINE=\"on_user_offline\",e.ON_STREAM_FALLBACK_UPDATE=\"on_stream_fallback_update\",e.ON_PUBLISH_STREAM=\"on_publish_stream\",e.ON_UPLINK_STATS=\"on_uplink_stats\",e.ON_P2P_LOST=\"on_p2p_lost\",e.ON_REMOVE_STREAM=\"on_remove_stream\",e.ON_ADD_AUDIO_STREAM=\"on_add_audio_stream\",e.ON_ADD_VIDEO_STREAM=\"on_add_video_stream\",e.ON_TOKEN_PRIVILEGE_WILL_EXPIRE=\"on_token_privilege_will_expire\",e.ON_TOKEN_PRIVILEGE_DID_EXPIRE=\"on_token_privilege_did_expire\",e.ON_USER_BANNED=\"on_user_banned\",e.ON_USER_LICENSE_BANNED=\"on_user_license_banned\",e.ON_NOTIFICATION=\"on_notification\",e.ON_CRYPT_ERROR=\"on_crypt_error\",e.MUTE_AUDIO=\"mute_audio\",e.MUTE_VIDEO=\"mute_video\",e.UNMUTE_AUDIO=\"unmute_audio\",e.UNMUTE_VIDEO=\"unmute_video\",e.ON_P2P_OK=\"on_p2p_ok\",e.RECEIVE_METADATA=\"receive_metadata\",e.ON_DATA_STREAM=\"on_data_stream\",e.ON_RTP_CAPABILITY_CHANGE=\"on_rtp_capability_change\",e.ON_REMOTE_DATASTREAM_UPDATE=\"on_remote_datastream_update\",e.ON_REMOTE_FULL_DATASTREAM_INFO=\"on_remote_full_datastream_info\",e.ENABLE_LOCAL_VIDEO=\"enable_local_video\",e.DISABLE_LOCAL_VIDEO=\"disable_local_video\",e.ENABLE_LOCAL_AUDIO=\"enable_local_audio\",e.DISABLE_LOCAL_AUDIO=\"disable_local_audio\",e.ON_PUBLISHED_USER_LIST=\"on_published_user_list\"}(fI||(fI={})),function(e){e.CONNECTION_STATE_CHANGE=\"CONNECTION_STATE_CHANGE\",e.NEED_ANSWER=\"NEED_ANSWER\",e.NEED_RENEGOTIATE=\"NEED_RENEGOTIATE\",e.P2P_LOST=\"P2P_LOST\",e.GATEWAY_P2P_LOST=\"GATEWAY_P2P_LOST\",e.NEED_UNPUB=\"NEED_UNPUB\",e.NEED_UNSUB=\"NEED_UNSUB\",e.NEED_UPLOAD=\"NEED_UPLOAD\",e.NEED_CONTROL=\"NEED_CONTROL\",e.START_RECONNECT=\"START_RECONNECT\",e.END_RECONNECT=\"END_RECONNECT\",e.NEED_SIGNAL_RTT=\"NEED_SIGNAL_RTT\"}(gI||(gI={})),function(e){e.SEND_ONLY=\"SEND_ONLY\",e.RECEIVE_ONLY=\"RECEIVE_ONLY\"}(TI||(TI={})),function(e){e.CONNECTED=\"websocket:connected\",e.RECONNECTING=\"websocket:reconnecting\",e.WILL_RECONNECT=\"websocket:will_reconnect\",e.CLOSED=\"websocket:closed\",e.FAILED=\"websocket:failed\",e.ON_MESSAGE=\"websocket:on_message\",e.REQUEST_NEW_URLS=\"websocket:request_new_urls\",e.RECONNECT_WAITTING_FINISH=\"websocket:reconnect_waitting_finish\",e.RECONNECT_CREATE_CONNECTION=\"websocket:reconnect_create_connection\",e.ON_TOKEN_PRIVILEGE_DID_EXPIRE=\"websocket:on_token_privilege_did_expire\"}(SI||(SI={}));class LI extends Kg{constructor(e){super(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:\"\",arguments.length>2?arguments[2]:void 0),sh(this,\"name\",\"AgoraRTCException\")}print(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:\"error\";return super.print(e,jC)}throw(){super.throw(jC)}}function kI(e){if(\"string\"!=typeof e||!/^[a-zA-Z0-9 \\!\\#\\$\\%\\&\\(\\)\\+\\-\\:\\;\\<\\=\\.\\>\\?\\@\\[\\]\\^\\_\\{\\}\\|\\~\\,]{1,64}$/.test(e))throw jC.error(\"Invalid Channel Name \".concat(e)),new LI(Hg.INVALID_PARAMS,\"The length must be within 64 bytes. The supported characters: a-z,A-Z,0-9,space,!, #, $, %, &, (, ), +, -, :, ;, <, =, ., >, ?, @, [, ], ^, _, {, }, |, ~, ,\")}function MI(e){if(!(t=e,\"number\"==typeof t&&Math.floor(t)===t&&0<=t&&t<=4294967295||$g(e,1,255)))throw new LI(Hg.INVALID_PARAMS,\"[String uid] Length of the string: [1,255]. ASCII characters only. [Number uid] The value range is [0,10000]\");var t;\"string\"==typeof e&&jC.warn(\"You input a string as the user ID, to ensure better end-user experience, Agora highly suggests not using a string as the user ID.\")}!function(e){e.TRANSCODE=\"mix_streaming\",e.RAW=\"raw_streaming\",e.INJECT=\"inject_streaming\"}(RI||(RI={})),function(e){e[e.INJECT_STREAM_STATUS_START_SUCCESS=0]=\"INJECT_STREAM_STATUS_START_SUCCESS\",e[e.INJECT_STREAM_STATUS_START_ALREADY_EXISTS=1]=\"INJECT_STREAM_STATUS_START_ALREADY_EXISTS\",e[e.INJECT_STREAM_STATUS_START_UNAUTHORIZED=2]=\"INJECT_STREAM_STATUS_START_UNAUTHORIZED\",e[e.INJECT_STREAM_STATUS_START_TIMEOUT=3]=\"INJECT_STREAM_STATUS_START_TIMEOUT\",e[e.INJECT_STREAM_STATUS_START_FAILED=4]=\"INJECT_STREAM_STATUS_START_FAILED\",e[e.INJECT_STREAM_STATUS_STOP_SUCCESS=5]=\"INJECT_STREAM_STATUS_STOP_SUCCESS\",e[e.INJECT_STREAM_STATUS_STOP_NOT_FOUND=6]=\"INJECT_STREAM_STATUS_STOP_NOT_FOUND\",e[e.INJECT_STREAM_STATUS_STOP_UNAUTHORIZED=7]=\"INJECT_STREAM_STATUS_STOP_UNAUTHORIZED\",e[e.INJECT_STREAM_STATUS_STOP_TIMEOUT=8]=\"INJECT_STREAM_STATUS_STOP_TIMEOUT\",e[e.INJECT_STREAM_STATUS_STOP_FAILED=9]=\"INJECT_STREAM_STATUS_STOP_FAILED\",e[e.INJECT_STREAM_STATUS_BROKEN=10]=\"INJECT_STREAM_STATUS_BROKEN\"}(CI||(CI={}));const UI={alpha:1,height:640,width:360,x:0,y:0,zOrder:0,audioChannel:0},xI={x:0,y:0,width:160,height:160,zOrder:255,alpha:1};function VI(e,t){Xg(e.url,\"\".concat(t,\".url\"),1,1e3,!1),Zg(e.x)||zg(e.x,\"\".concat(t,\".x\"),0,1e4),Zg(e.y)||zg(e.y,\"\".concat(t,\".y\"),0,1e4),Zg(e.width)||zg(e.width,\"\".concat(t,\".width\"),0,1e4),Zg(e.height)||zg(e.height,\"\".concat(t,\".height\"),0,1e4),Zg(e.zOrder)||zg(e.zOrder,\"\".concat(t,\".zOrder\"),0,255),Zg(e.alpha)||zg(e.alpha,\"\".concat(t,\".alpha\"),0,1,!1)}const FI={audioBitrate:48,audioChannels:1,audioSampleRate:48e3,backgroundColor:0,height:360,lowLatency:!1,videoBitrate:400,videoCodecProfile:100,videoCodecType:1,videoFrameRate:15,videoGop:30,width:640,images:[],userConfigs:[],userConfigExtraInfo:\"\"},BI={audioBitrate:48,audioChannels:2,audioVolume:100,audioSampleRate:48e3,height:0,width:0,videoBitrate:400,videoFramerate:15,videoGop:30};var jI,GI,WI,HI,KI,YI,qI,zI,JI,XI,QI,ZI,$I,ev;function tv(e){if(!e.channelName)throw new LI(Hg.INVALID_PARAMS,\"invalid channelName in info\");if(\"number\"!=typeof e.uid)throw new LI(Hg.INVALID_PARAMS,\"invalid uid in info, uid must be a number\");return e.token&&Xg(e.token,\"info.token\",1,2047),MI(e.uid),kI(e.channelName),!0}!function(e){e.WARNING=\"@live_uap-warning\",e.ERROR=\"@line_uap-error\",e.PUBLISH_STREAM_STATUS=\"@live_uap-publish-status\",e.INJECT_STREAM_STATUS=\"@live_uap-inject-status\",e.WORKER_STATUS=\"@live_uap-worker-status\",e.REQUEST_NEW_ADDRESS=\"@live_uap-request-address\"}(jI||(jI={})),function(e){e.REQUEST_WORKER_MANAGER_LIST=\"@live_req_worker_manager\"}(GI||(GI={})),function(e){e[e.LIVE_STREAM_RESPONSE_SUCCEED=200]=\"LIVE_STREAM_RESPONSE_SUCCEED\",e[e.LIVE_STREAM_RESPONSE_ALREADY_EXISTS_STREAM=454]=\"LIVE_STREAM_RESPONSE_ALREADY_EXISTS_STREAM\",e[e.LIVE_STREAM_RESPONSE_TRANSCODING_PARAMETER_ERROR=450]=\"LIVE_STREAM_RESPONSE_TRANSCODING_PARAMETER_ERROR\",e[e.LIVE_STREAM_RESPONSE_BAD_STREAM=451]=\"LIVE_STREAM_RESPONSE_BAD_STREAM\",e[e.LIVE_STREAM_RESPONSE_WM_PARAMETER_ERROR=400]=\"LIVE_STREAM_RESPONSE_WM_PARAMETER_ERROR\",e[e.LIVE_STREAM_RESPONSE_WM_WORKER_NOT_EXIST=404]=\"LIVE_STREAM_RESPONSE_WM_WORKER_NOT_EXIST\",e[e.LIVE_STREAM_RESPONSE_NOT_AUTHORIZED=456]=\"LIVE_STREAM_RESPONSE_NOT_AUTHORIZED\",e[e.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE=457]=\"LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE\",e[e.LIVE_STREAM_RESPONSE_REQUEST_TOO_OFTEN=429]=\"LIVE_STREAM_RESPONSE_REQUEST_TOO_OFTEN\",e[e.LIVE_STREAM_RESPONSE_NOT_FOUND_PUBLISH=452]=\"LIVE_STREAM_RESPONSE_NOT_FOUND_PUBLISH\",e[e.LIVE_STREAM_RESPONSE_NOT_SUPPORTED=453]=\"LIVE_STREAM_RESPONSE_NOT_SUPPORTED\",e[e.LIVE_STREAM_RESPONSE_MAX_STREAM_NUM=455]=\"LIVE_STREAM_RESPONSE_MAX_STREAM_NUM\",e[e.LIVE_STREAM_RESPONSE_INTERNAL_SERVER_ERROR=500]=\"LIVE_STREAM_RESPONSE_INTERNAL_SERVER_ERROR\",e[e.LIVE_STREAM_RESPONSE_WORKER_LOST=501]=\"LIVE_STREAM_RESPONSE_WORKER_LOST\",e[e.LIVE_STREAM_RESPONSE_RESOURCE_LIMIT=502]=\"LIVE_STREAM_RESPONSE_RESOURCE_LIMIT\",e[e.LIVE_STREAM_RESPONSE_WORKER_QUIT=503]=\"LIVE_STREAM_RESPONSE_WORKER_QUIT\",e[e.ERROR_FAIL_SEND_MESSAGE=504]=\"ERROR_FAIL_SEND_MESSAGE\",e[e.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE=30]=\"PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE\",e[e.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT=31]=\"PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT\",e[e.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH=32]=\"PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH\",e[e.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN=33]=\"PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN\"}(WI||(WI={})),function(e){e.CONNECT_FAILED=\"connect failed\",e.CONNECT_TIMEOUT=\"connect timeout\",e.WS_DISCONNECTED=\"websocket disconnected\",e.REQUEST_TIMEOUT=\"request timeout\",e.REQUEST_FAILED=\"request failed\",e.WAIT_STATUS_TIMEOUT=\"wait status timeout\",e.WAIT_STATUS_ERROR=\"wait status error\",e.BAD_STATE=\"bad state\",e.WS_ABORT=\"ws abort\",e.AP_REQUEST_TIMEOUT=\"AP request timeout\",e.AP_JSON_PARSE_ERROR=\"AP json parse error\",e.AP_REQUEST_ERROR=\"AP request error\",e.AP_REQUEST_ABORT=\"AP request abort\"}(HI||(HI={})),function(e){e[e.SetSdkProfile=0]=\"SetSdkProfile\",e[e.SetSourceChannel=1]=\"SetSourceChannel\",e[e.SetSourceUserId=2]=\"SetSourceUserId\",e[e.SetDestChannel=3]=\"SetDestChannel\",e[e.StartPacketTransfer=4]=\"StartPacketTransfer\",e[e.StopPacketTransfer=5]=\"StopPacketTransfer\",e[e.UpdateDestChannel=6]=\"UpdateDestChannel\",e[e.Reconnect=7]=\"Reconnect\",e[e.SetVideoProfile=8]=\"SetVideoProfile\"}(KI||(KI={})),function(e){e.NETWORK_DISCONNECTED=\"NETWORK_DISCONNECTED\",e.NETWORK_CONNECTED=\"NETWORK_CONNECTED\",e.PACKET_JOINED_SRC_CHANNEL=\"PACKET_JOINED_SRC_CHANNEL\",e.PACKET_JOINED_DEST_CHANNEL=\"PACKET_JOINED_DEST_CHANNEL\",e.PACKET_SENT_TO_DEST_CHANNEL=\"PACKET_SENT_TO_DEST_CHANNEL\",e.PACKET_RECEIVED_VIDEO_FROM_SRC=\"PACKET_RECEIVED_VIDEO_FROM_SRC\",e.PACKET_RECEIVED_AUDIO_FROM_SRC=\"PACKET_RECEIVED_AUDIO_FROM_SRC\",e.PACKET_UPDATE_DEST_CHANNEL=\"PACKET_UPDATE_DEST_CHANNEL\",e.PACKET_UPDATE_DEST_CHANNEL_REFUSED=\"PACKET_UPDATE_DEST_CHANNEL_REFUSED\",e.PACKET_UPDATE_DEST_CHANNEL_NOT_CHANGE=\"PACKET_UPDATE_DEST_CHANNEL_NOT_CHANGE\"}(YI||(YI={})),function(e){e.RELAY_STATE_IDLE=\"RELAY_STATE_IDLE\",e.RELAY_STATE_CONNECTING=\"RELAY_STATE_CONNECTING\",e.RELAY_STATE_RUNNING=\"RELAY_STATE_RUNNING\",e.RELAY_STATE_FAILURE=\"RELAY_STATE_FAILURE\"}(qI||(qI={})),function(e){e.RELAY_OK=\"RELAY_OK\",e.SERVER_CONNECTION_LOST=\"SERVER_CONNECTION_LOST\",e.SRC_TOKEN_EXPIRED=\"SRC_TOKEN_EXPIRED\",e.DEST_TOKEN_EXPIRED=\"DEST_TOKEN_EXPIRED\"}(zI||(zI={})),function(e){e.High=\"high\",e.Low=\"low\",e.Audio=\"audio\",e.Screen=\"screen\",e.ScreenLow=\"screen_low\"}(JI||(JI={})),function(e){e.DISCONNECT=\"disconnect\",e.CONNECTION_STATE_CHANGE=\"connection-state-change\",e.NETWORK_QUALITY=\"network-quality\",e.STREAM_TYPE_CHANGE=\"stream-type-change\",e.IS_P2P_DISCONNECTED=\"is-p2p-dis\",e.DISCONNECT_P2P=\"dis-p2p\",e.REQUEST_NEW_GATEWAY_LIST=\"req-gate-url\",e.NEED_RENEW_SESSION=\"need-sid\",e.REQUEST_P2P_CONNECTION_PARAMS=\"request-p2p-connection-params\",e.JOIN_RESPONSE=\"join-response\",e.REQUEST_DC_CONNECTION_PARAMS=\"request-dc-connection-params\",e.RESET_CONNECTION_EVENTS=\"reset-connection-events\",e.DATACHANNEL_PRECONNECT=\"datachannel_preconnect\",e.DATACHANNEL_FAILBACK=\"datachannel_failback\",e.RESET_SIGNAL=\"reset-signal\"}(XI||(XI={})),function(e){e.P2P_DISCONNECTED=\"P2P_DISCONNECTED\",e.A_ROUND_WS_FAILED=\"A_ROUND_WS_FAILED\",e.TIMEOUT=\"TIMEOUT\",e.UNKNOWN_REASON=\"UNKNOWN_REASON\"}(QI||(QI={})),function(e){e[e.Nothing=0]=\"Nothing\",e[e.Audio=1]=\"Audio\",e[e.LwoVideo=2]=\"LwoVideo\",e[e.Video=4]=\"Video\",e[e.Data=8]=\"Data\",e[e.DataStream0=256]=\"DataStream0\",e[e.DataStream1=512]=\"DataStream1\",e[e.DataStream2=1024]=\"DataStream2\",e[e.DataStream3=2048]=\"DataStream3\",e[e.DataStream4=4096]=\"DataStream4\",e[e.DataStream5=8192]=\"DataStream5\",e[e.DataStream6=16384]=\"DataStream6\",e[e.DataStream7=32768]=\"DataStream7\"}(ZI||(ZI={})),function(e){e[e.websocket=0]=\"websocket\",e[e.datachannel=1]=\"datachannel\"}($I||($I={})),function(e){e.CHINA=\"CHINA\",e.ASIA=\"ASIA\",e.NORTH_AMERICA=\"NORTH_AMERICA\",e.EUROPE=\"EUROPE\",e.JAPAN=\"JAPAN\",e.INDIA=\"INDIA\",e.KOREA=\"KOREA\",e.HKMC=\"HKMC\",e.US=\"US\",e.OCEANIA=\"OCEANIA\",e.SOUTH_AMERICA=\"SOUTH_AMERICA\",e.AFRICA=\"AFRICA\",e.OVERSEA=\"OVERSEA\",e.GLOBAL=\"GLOBAL\",e.EXTENSIONS=\"EXTENSIONS\"}(ev||(ev={}));const iv=[ev.AFRICA,ev.ASIA,ev.CHINA,ev.EUROPE,ev.GLOBAL,ev.INDIA,ev.JAPAN,ev.NORTH_AMERICA,ev.OCEANIA,ev.OVERSEA,ev.SOUTH_AMERICA];var nv;!function(e){e.CHINA=\"CN\",e.ASIA=\"AS\",e.NORTH_AMERICA=\"NA\",e.EUROPE=\"EU\",e.JAPAN=\"JP\",e.INDIA=\"IN\",e.KOREA=\"KR\",e.HKMC=\"HK\",e.US=\"US\",e.OCEANIA=\"OC\",e.SOUTH_AMERICA=\"SA\",e.AFRICA=\"AF\",e.OVERSEA=\"OVERSEA\",e.GLOBAL=\"GLOBAL\",e.EXTENSIONS=\"GLOBAL\"}(nv||(nv={}));const rv={CHINA:{},ASIA:{CODE:nv.ASIA,WEBCS_DOMAIN:[\"ap-web-1-asia.agora.io\"],WEBCS_DOMAIN_BACKUP_LIST:[\"ap-web-2-asia.agora.io\"],PROXY_CS:[\"proxy-ap-web-asia.agora.io\"],CDS_AP:[\"cds-ap-web-asia.agora.io\",\"cds-ap-web-asia2.agora.io\"],ACCOUNT_REGISTER:[\"sua-ap-web-asia.agora.io\",\"sua-ap-web-asia2.agora.io\"],UAP_AP:[\"uap-ap-web-asia.agora.io\",\"uap-ap-web-asia2.agora.io\"],EVENT_REPORT_DOMAIN:[\"statscollector-1-asia.agora.io\"],EVENT_REPORT_BACKUP_DOMAIN:[\"statscollector-2-asia.agora.io\"],LOG_UPLOAD_SERVER:[\"logservice-asia.agora.io\"],PROXY_SERVER_TYPE3:[\"southeast-asia.webrtc-cloud-proxy.sd-rtn.com\"]},NORTH_AMERICA:{CODE:nv.NORTH_AMERICA,WEBCS_DOMAIN:[\"ap-web-1-north-america.agora.io\"],WEBCS_DOMAIN_BACKUP_LIST:[\"ap-web-2-north-america.agora.io\"],PROXY_CS:[\"proxy-ap-web-america.agora.io\"],CDS_AP:[\"cds-ap-web-america.agora.io\",\"cds-ap-web-america2.agora.io\"],ACCOUNT_REGISTER:[\"sua-ap-web-america.agora.io\",\"sua-ap-web-america2.agora.io\"],UAP_AP:[\"uap-ap-web-america.agora.io\",\"uap-ap-web-america2.agora.io\"],EVENT_REPORT_DOMAIN:[\"statscollector-1-north-america.agora.io\"],EVENT_REPORT_BACKUP_DOMAIN:[\"statscollector-2-north-america.agora.io\"],LOG_UPLOAD_SERVER:[\"logservice-north-america.agora.io\"],PROXY_SERVER_TYPE3:[\"east-usa.webrtc-cloud-proxy.sd-rtn.com\"]},EUROPE:{CODE:nv.EUROPE,WEBCS_DOMAIN:[\"ap-web-1-europe.agora.io\"],WEBCS_DOMAIN_BACKUP_LIST:[\"ap-web-2-europe.agora.io\"],PROXY_CS:[\"proxy-ap-web-europe.agora.io\"],CDS_AP:[\"cds-ap-web-europe.agora.io\",\"cds-ap-web-europe2.agora.io\"],ACCOUNT_REGISTER:[\"sua-ap-web-europe.agora.io\",\"sua-ap-web-europe.agora.io\"],UAP_AP:[\"uap-ap-web-europe.agora.io\",\"uap-ap-web-europe2.agora.io\"],EVENT_REPORT_DOMAIN:[\"statscollector-1-europe.agora.io\"],EVENT_REPORT_BACKUP_DOMAIN:[\"statscollector-2-europe.agora.io\"],LOG_UPLOAD_SERVER:[\"logservice-europe.agora.io\"],PROXY_SERVER_TYPE3:[\"europe.webrtc-cloud-proxy.sd-rtn.com\"]},JAPAN:{CODE:nv.JAPAN,WEBCS_DOMAIN:[\"ap-web-1-japan.agora.io\"],WEBCS_DOMAIN_BACKUP_LIST:[\"ap-web-2-japan.agora.io\"],PROXY_CS:[\"proxy-ap-web-japan.agora.io\"],CDS_AP:[\"cds-ap-web-japan.agora.io\",\"cds-ap-web-japan2.agora.io\"],ACCOUNT_REGISTER:[\"sua-ap-web-japan.agora.io\",\"sua-ap-web-japan2.agora.io\"],UAP_AP:[\"uap-ap-web-japan.agora.io\",\"uap-ap-web-japan2.agora.io\"],EVENT_REPORT_DOMAIN:[\"statscollector-1-japan.agora.io\"],EVENT_REPORT_BACKUP_DOMAIN:[\"statscollector-2-japan.agora.io\"],LOG_UPLOAD_SERVER:[\"logservice-japan.agora.io\"],PROXY_SERVER_TYPE3:[\"japan.webrtc-cloud-proxy.sd-rtn.com\"]},INDIA:{CODE:nv.INDIA,WEBCS_DOMAIN:[\"ap-web-1-india.agora.io\"],WEBCS_DOMAIN_BACKUP_LIST:[\"ap-web-2-india.agora.io\"],PROXY_CS:[\"proxy-ap-web-india.agora.io\"],CDS_AP:[\"cds-ap-web-india.agora.io\",\"cds-ap-web-india2.agora.io\"],ACCOUNT_REGISTER:[\"sua-ap-web-india.agora.io\",\"sua-ap-web-india2.agora.io\"],UAP_AP:[\"uap-ap-web-india.agora.io\",\"uap-ap-web-india2.agora.io\"],EVENT_REPORT_DOMAIN:[\"statscollector-1-india.agora.io\"],EVENT_REPORT_BACKUP_DOMAIN:[\"statscollector-2-india.agora.io\"],LOG_UPLOAD_SERVER:[\"logservice-india.agora.io\"],PROXY_SERVER_TYPE3:[\"india.webrtc-cloud-proxy.sd-rtn.com\"]},KOREA:{CODE:nv.KOREA,WEBCS_DOMAIN:[\"ap-web-1-korea.agora.io\"],WEBCS_DOMAIN_BACKUP_LIST:[\"ap-web-2-korea.agora.io\"],PROXY_CS:[\"proxy-ap-web-korea.agora.io\"],CDS_AP:[\"cds-ap-web-korea.agora.io\",\"cds-ap-web-korea2.agora.io\"],ACCOUNT_REGISTER:[\"sua-ap-web-korea.agora.io\",\"sua-ap-web-korea2.agora.io\"],UAP_AP:[\"uap-ap-web-korea.agora.io\",\"uap-ap-web-korea2.agora.io\"],EVENT_REPORT_DOMAIN:[\"statscollector-1-korea.agora.io\"],EVENT_REPORT_BACKUP_DOMAIN:[\"statscollector-2-korea.agora.io\"],LOG_UPLOAD_SERVER:[\"logservice-korea.agora.io\"],PROXY_SERVER_TYPE3:[\"korea.webrtc-cloud-proxy.sd-rtn.com\"]},HKMC:{CODE:nv.HKMC,WEBCS_DOMAIN:[\"ap-web-1-hkmc.agora.io\"],WEBCS_DOMAIN_BACKUP_LIST:[\"ap-web-2-hkmc.agora.io\"],PROXY_CS:[\"proxy-ap-web-hkmc.agora.io\"],CDS_AP:[\"cds-ap-web-hkmc.agora.io\",\"cds-ap-web-hkmc2.agora.io\"],ACCOUNT_REGISTER:[\"sua-ap-web-hkmc.agora.io\",\"sua-ap-web-hkmc2.agora.io\"],UAP_AP:[\"uap-ap-web-hkmc.agora.io\",\"uap-ap-web-hkmc2.agora.io\"],EVENT_REPORT_DOMAIN:[\"statscollector-1-hkmc.agora.io\"],EVENT_REPORT_BACKUP_DOMAIN:[\"statscollector-2-hkmc.agora.io\"],LOG_UPLOAD_SERVER:[\"logservice-hkmc.agora.io\"],PROXY_SERVER_TYPE3:[\"hkmc.webrtc-cloud-proxy.sd-rtn.com\"]},US:{CODE:nv.US,WEBCS_DOMAIN:[\"ap-web-1-us.agora.io\"],WEBCS_DOMAIN_BACKUP_LIST:[\"ap-web-2-us.agora.io\"],PROXY_CS:[\"proxy-ap-web-us.agora.io\"],CDS_AP:[\"cds-ap-web-us.agora.io\",\"cds-ap-web-us2.agora.io\"],ACCOUNT_REGISTER:[\"sua-ap-web-us.agora.io\",\"sua-ap-web-us2.agora.io\"],UAP_AP:[\"uap-ap-web-us.agora.io\",\"uap-ap-web-us2.agora.io\"],EVENT_REPORT_DOMAIN:[\"statscollector-1-us.agora.io\"],EVENT_REPORT_BACKUP_DOMAIN:[\"statscollector-2-us.agora.io\"],LOG_UPLOAD_SERVER:[\"logservice-us.agora.io\"],PROXY_SERVER_TYPE3:[\"us.webrtc-cloud-proxy.sd-rtn.com\"]},OVERSEA:{CODE:nv.OVERSEA,WEBCS_DOMAIN:[\"ap-web-1-oversea.agora.io\"],WEBCS_DOMAIN_BACKUP_LIST:[\"ap-web-2-oversea.agora.io\"],PROXY_CS:[\"proxy-ap-web-oversea.agora.io\"],CDS_AP:[\"cds-ap-web-oversea.agora.io\"],ACCOUNT_REGISTER:[\"sua-ap-web-oversea.agora.io\"],UAP_AP:[\"uap-ap-web-oversea.agora.io\"],EVENT_REPORT_DOMAIN:[\"statscollector-1-oversea.agora.io\"],EVENT_REPORT_BACKUP_DOMAIN:[\"statscollector-2-oversea.agora.io\"],LOG_UPLOAD_SERVER:[\"logservice-oversea.agora.io\"],PROXY_SERVER_TYPE3:[\"webrtc-cloud-proxy.agora.io\"]},GLOBAL:{CODE:nv.GLOBAL,WEBCS_DOMAIN:[\"webrtc2-ap-web-1.agora.io\"],WEBCS_DOMAIN_BACKUP_LIST:[\"webrtc2-ap-web-3.agora.io\"],PROXY_CS:[\"ap-proxy-1.agora.io\",\"ap-proxy-2.agora.io\"],CDS_AP:[\"cds-ap-web-1.agora.io\",\"cds-ap-web-3.agora.io\"],ACCOUNT_REGISTER:[\"sua-ap-web-1.agora.io\",\"sua-ap-web-3.agora.io\"],UAP_AP:[\"uap-ap-web-1.agora.io\",\"uap-ap-web-3.agora.io\"],EVENT_REPORT_DOMAIN:[\"statscollector-1.agora.io\"],EVENT_REPORT_BACKUP_DOMAIN:[\"statscollector-2.agora.io\"],LOG_UPLOAD_SERVER:[\"logservice.agora.io\"],PROXY_SERVER_TYPE3:[\"webrtc-cloud-proxy.sd-rtn.com\"]},OCEANIA:{CODE:nv.OCEANIA,WEBCS_DOMAIN:[\"ap-web-1-oceania.agora.io\"],WEBCS_DOMAIN_BACKUP_LIST:[\"ap-web-2-oceania.agora.io\"],PROXY_CS:[\"proxy-ap-web-oceania.agora.io\"],CDS_AP:[\"cds-ap-web-oceania.agora.io\",\"cds-ap-web-oceania2.agora.io\"],ACCOUNT_REGISTER:[\"sua-ap-web-oceania.agora.io\",\"sua-ap-web-oceania2.agora.io\"],UAP_AP:[\"uap-ap-web-oceania.agora.io\",\"uap-ap-web-oceania2.agora.io\"],EVENT_REPORT_DOMAIN:[\"statscollector-1-oceania.agora.io\"],EVENT_REPORT_BACKUP_DOMAIN:[\"statscollector-2-oceania.agora.io\"],LOG_UPLOAD_SERVER:[\"logservice-oceania.agora.io\"],PROXY_SERVER_TYPE3:[\"oceania.webrtc-cloud-proxy.sd-rtn.com\"]},SOUTH_AMERICA:{CODE:nv.SOUTH_AMERICA,WEBCS_DOMAIN:[\"ap-web-1-south-america.agora.io\"],WEBCS_DOMAIN_BACKUP_LIST:[\"ap-web-2-south-america.agora.io\"],PROXY_CS:[\"proxy-ap-web-south-america.agora.io\"],CDS_AP:[\"cds-ap-web-south-america.agora.io\",\"cds-ap-web-south-america2.agora.io\"],ACCOUNT_REGISTER:[\"sua-ap-web-south-america.agora.io\",\"sua-ap-web-south-america2.agora.io\"],UAP_AP:[\"uap-ap-web-south-america.agora.io\",\"uap-ap-web-south-america2.agora.io\"],EVENT_REPORT_DOMAIN:[\"statscollector-1-south-america.agora.io\"],EVENT_REPORT_BACKUP_DOMAIN:[\"statscollector-2-south-america.agora.io\"],LOG_UPLOAD_SERVER:[\"logservice-south-america.agora.io\"],PROXY_SERVER_TYPE3:[\"south-america.webrtc-cloud-proxy.sd-rtn.com\"]},AFRICA:{CODE:nv.AFRICA,WEBCS_DOMAIN:[\"ap-web-1-africa.agora.io\"],WEBCS_DOMAIN_BACKUP_LIST:[\"ap-web-2-africa.agora.io\"],PROXY_CS:[\"proxy-ap-web-africa.agora.io\"],CDS_AP:[\"cds-ap-web-africa.agora.io\",\"cds-ap-web-africa2.agora.io\"],ACCOUNT_REGISTER:[\"sua-ap-web-africa.agora.io\",\"sua-ap-web-africa2.agora.io\"],UAP_AP:[\"uap-ap-web-africa.agora.io\",\"uap-ap-web-africa2.agora.io\"],EVENT_REPORT_DOMAIN:[\"statscollector-1-africa.agora.io\"],EVENT_REPORT_BACKUP_DOMAIN:[\"statscollector-2-africa.agora.io\"],LOG_UPLOAD_SERVER:[\"logservice-south-africa.agora.io\"],PROXY_SERVER_TYPE3:[\"africa.webrtc-cloud-proxy.sd-rtn.com\"]},EXTENSIONS:{}};var sv,ov,av,cv,dv,lv,uv,hv,pv,_v,Ev,mv,fv,gv,Tv,Sv,Rv,Cv,Iv,vv,yv,Av,bv,wv;mC&&(rv.CHINA={CODE:nv.CHINA,WEBCS_DOMAIN:[\"webrtc2-2.ap.sd-rtn.com\"],WEBCS_DOMAIN_BACKUP_LIST:[\"webrtc2-4.ap.sd-rtn.com\"],PROXY_CS:[\"proxy-web.ap.sd-rtn.com\"],CDS_AP:[\"cds-web-2.ap.sd-rtn.com\",\"cds-web-4.ap.sd-rtn.com\"],ACCOUNT_REGISTER:[\"sua-web-2.ap.sd-rtn.com\",\"sua-web-4.ap.sd-rtn.com\"],UAP_AP:[\"uap-web-2.ap.sd-rtn.com\",\"uap-web-4.ap.sd-rtn.com\"],EVENT_REPORT_DOMAIN:[\"web-3.statscollector.sd-rtn.com\"],EVENT_REPORT_BACKUP_DOMAIN:[\"web-4.statscollector.sd-rtn.com\"],LOG_UPLOAD_SERVER:[\"logservice-china.agora.io\"],PROXY_SERVER_TYPE3:[\"east-cn.webrtc-cloud-proxy.sd-rtn.com\"]}),function(e){e.UPDATE_BITRATE_LIMIT=\"update_bitrate_limit\"}(sv||(sv={}));class Ov extends dT{constructor(e,t){super(),sh(this,\"onICEConnectionStateChange\",void 0),sh(this,\"onConnectionStateChange\",void 0),sh(this,\"onDTLSTransportStateChange\",void 0),sh(this,\"onDTLSTransportError\",void 0),sh(this,\"onICETransportStateChange\",void 0),sh(this,\"onFirstAudioReceived\",void 0),sh(this,\"onFirstVideoReceived\",void 0),sh(this,\"onFirstAudioDecoded\",void 0),sh(this,\"onFirstVideoDecoded\",void 0),sh(this,\"onFirstVideoDecodedTimeout\",void 0),sh(this,\"onSelectedLocalCandidateChanged\",void 0),sh(this,\"onSelectedRemoteCandidateChanged\",void 0)}}class Nv extends Ov{constructor(e,t){super(e,t)}}!function(e){e.SEND=\"sendonly\",e.RECV=\"recvonly\",e.SENDRECV=\"sendrecv\",e.INACTIVE=\"inactive\"}(ov||(ov={})),function(e){e.VIDEO=\"video\",e.AUDIO=\"audio\"}(av||(av={})),function(e){e[e.UDP=0]=\"UDP\",e[e.TCP=1]=\"TCP\",e[e.RELAY=2]=\"RELAY\"}(cv||(cv={})),function(e){e[e.FIRST_CONNECTION=0]=\"FIRST_CONNECTION\",e[e.TCP_RESTART=1]=\"TCP_RESTART\",e[e.RELAY_RESTART=2]=\"RELAY_RESTART\",e[e.OLD_FIRST_CONNECTION=10]=\"OLD_FIRST_CONNECTION\",e[e.OLD_RESTART=11]=\"OLD_RESTART\",e[e.DISCONNECTED_OR_FAILED=20]=\"DISCONNECTED_OR_FAILED\"}(dv||(dv={})),function(e){e.LocalVideoTrack=\"videoTrack\",e.LocalAudioTrack=\"audioTrack\",e.LocalVideoLowTrack=\"videoLowTrack\"}(lv||(lv={})),function(e){e.New=\"new\",e.Connected=\"connected\",e.Reconnecting=\"reconnecting\",e.Disconnected=\"disconnected\"}(uv||(uv={})),function(e){e.StateChange=\"stateChange\",e.IceConnectionStateChange=\"iceConnectionStateChange\",e.RequestMuteLocal=\"requestMuteLocal\",e.RequestUnmuteLocal=\"requestUnmuteLocal\",e.RequestRePublish=\"requestRePublish\",e.RequestRePublishDataChannel=\"requestRePublishDataChannel\",e.RequestReSubscribe=\"requestReSubscribe\",e.RequestUploadStats=\"requestUploadStats\",e.RequestUpload=\"requestUpload\",e.MediaReconnectStart=\"MediaReconnectStart\",e.MediaReconnectEnd=\"MediaReconnectEnd\",e.NeedSignalRTT=\"NeedSignalRTT\",e.RequestRestartICE=\"RequestRestartIce\",e.PeerConnectionStateChange=\"PeerConnectionStateChange\",e.RequestReconnect=\"RequestReconnect\",e.RequestReconnectPC=\"RequestReconnectPC\",e.RequestUnpublishForReconnectPC=\"RequestUnpublishForReconnectPC\",e.P2PLost=\"P2PLost\",e.UpdateVideoEncoder=\"UpdateVideoEncoder\",e.ConnectionTypeChange=\"ConnectionTypeChange\",e.RequestLowStreamParameter=\"RequestLowStreamParameter\",e.QueryClientConnectionState=\"QueryClientConnectionState\",e.LocalCandidate=\"LocalCandidate\",e.RequestP2PMuteLocal=\"requestP2PMuteLocal\",e.RequestP2PUnPublish=\"RequestP2PUnPublish\",e.RequestP2PUnmuteRemote=\"RequestP2PUnmuteRemote\",e.RequestP2PMuteRemote=\"RequestP2PMuteRemote\",e.RequestP2PRestartICE=\"RequestP2PRestartICE\"}(hv||(hv={})),function(e){e.MUTE_LOCAL_VIDEO=\"mute_local_video\",e.MUTE_LOCAL_AUDIO=\"mute_local_audio\",e.UNMUTE_LOCAL_VIDEO=\"unmute_local_video\",e.UNMUTE_LOCAL_AUDIO=\"unmute_local_audio\",e.MUTE_REMOTE_VIDEO=\"mute_remote_video\",e.MUTE_REMOTE_AUDIO=\"mute_remote_audio\",e.UNMUTE_REMOTE_VIDEO=\"unmute_remote_video\",e.UNMUTE_REMOTE_AUDIO=\"unmute_remote_audio\"}(pv||(pv={})),function(e){e.CONNECTING=\"CONNECTING\",e.RECONNECTING=\"RECONNECTING\",e.CONNECTED=\"CONNECTED\",e.CLOSED=\"CLOSED\"}(_v||(_v={})),function(e){e[e.CONNECT_AP=0]=\"CONNECT_AP\",e[e.AP_CONNECTED=1]=\"AP_CONNECTED\",e[e.CONNECT_WORKER_MANAGER=2]=\"CONNECT_WORKER_MANAGER\",e[e.WORKER_MANAGER_CONNECTED=3]=\"WORKER_MANAGER_CONNECTED\",e[e.GET_WORKER_MANAGER_RESPONSE=4]=\"GET_WORKER_MANAGER_RESPONSE\",e[e.CONNECT_WORKER=5]=\"CONNECT_WORKER\",e[e.WORKER_CONNECTED=6]=\"WORKER_CONNECTED\",e[e.CLOSED=7]=\"CLOSED\"}(Ev||(Ev={})),function(e){e.CONNECTION_STATE_CHANGE=\"connection-state-change\",e.STATE_CHANGE=\"state-change\",e.INSPECT_RESULT=\"inspect-result\",e.CLIENT_LOCAL_VIDEO_TRACK=\"client-local-video-track\",e.REQUEST_NEW_WORKER_URL=\"request-new-worker-url\"}(mv||(mv={})),function(e){e.NETWORK_ERROR=\"NETWORK_ERROR\",e.SERVER_ERROR=\"SERVER_ERROR\",e.MULTI_IP=\"MULTI_IP\",e.TIMEOUT=\"TIMEOUT\",e.OFFLINE=\"OFFLINE\",e.LEAVE=\"LEAVE\",e.P2P_FAILED=\"P2P_FAILED\",e.FALLBACK=\"FALLBACK\"}(fv||(fv={})),function(e){e.CONNECTED=\"transmitter:connected\",e.RECONNECTING=\"transmitter:reconnecting\",e.WILL_RECONNECT=\"transmitter:will_reconnect\",e.CLOSED=\"transmitter:closed\",e.FAILED=\"transmitter:failed\",e.ON_MESSAGE=\"transmitter:on_message\",e.REQUEST_NEW_URLS=\"transmitter:request_new_urls\",e.RECONNECT_WAITTING_FINISH=\"transmitter:reconnect_waitting_finish\",e.RECONNECT_CREATE_CONNECTION=\"transmitter:reconnect_create_connection\",e.ON_TOKEN_PRIVILEGE_DID_EXPIRE=\"transmitter:on_token_privilege_did_expire\",e.TO_CONNECT_DATACHANNEL=\"transmitter:to_connect_datachannel\",e.FAILBACK=\"transmitter:failback\"}(gv||(gv={})),function(e){e.CAMERA_CHANGED=\"camera-changed\",e.MICROPHONE_CHANGED=\"microphone-changed\",e.PLAYBACK_DEVICE_CHANGED=\"playback-device-changed\",e.AUDIO_AUTOPLAY_FAILED=\"audio-autoplay-failed\",e.AUTOPLAY_FAILED=\"autoplay-failed\",e.AUDIO_CONTEXT_STATE_CHANGED=\"audio-context-state-changed\",e.SECURITY_POLICY_VIOLATION=\"security-policy-violation\"}(Tv||(Tv={})),function(e){e[e.APP_TYPE_INVALID_VALUE=-1]=\"APP_TYPE_INVALID_VALUE\",e[e.APP_TYPE_NATIVE=0]=\"APP_TYPE_NATIVE\",e[e.APP_TYPE_NATIVE_COCOS=1]=\"APP_TYPE_NATIVE_COCOS\",e[e.APP_TYPE_NATIVE_UNITY=2]=\"APP_TYPE_NATIVE_UNITY\",e[e.APP_TYPE_NATIVE_ELECTRON=3]=\"APP_TYPE_NATIVE_ELECTRON\",e[e.APP_TYPE_NATIVE_FLUTTER=4]=\"APP_TYPE_NATIVE_FLUTTER\",e[e.APP_TYPE_NATIVE_UNREAL=5]=\"APP_TYPE_NATIVE_UNREAL\",e[e.APP_TYPE_NATIVE_XAMARIN=6]=\"APP_TYPE_NATIVE_XAMARIN\",e[e.APP_TYPE_NATIVE_API_CLOUD=7]=\"APP_TYPE_NATIVE_API_CLOUD\",e[e.APP_TYPE_NATIVE_REACT_NATIVE=8]=\"APP_TYPE_NATIVE_REACT_NATIVE\",e[e.APP_TYPE_NATIVE_PYTHON=9]=\"APP_TYPE_NATIVE_PYTHON\",e[e.APP_TYPE_NATIVE_COCOS_CREATOR=10]=\"APP_TYPE_NATIVE_COCOS_CREATOR\",e[e.APP_TYPE_NATIVE_RUST=11]=\"APP_TYPE_NATIVE_RUST\",e[e.APP_TYPE_NATIVE_C_SHARP=12]=\"APP_TYPE_NATIVE_C_SHARP\",e[e.APP_TYPE_NATIVE_CEF=13]=\"APP_TYPE_NATIVE_CEF\",e[e.APP_TYPE_NATIVE_UNI_APP=14]=\"APP_TYPE_NATIVE_UNI_APP\",e[e.APP_TYPE_WEBRTC=1e3]=\"APP_TYPE_WEBRTC\",e[e.APP_TYPE_WEBRTC_REACT=1001]=\"APP_TYPE_WEBRTC_REACT\",e[e.APP_TYPE_WEBRTC_VUE=1002]=\"APP_TYPE_WEBRTC_VUE\",e[e.APP_TYPE_WEBRTC_ANGULAR=1003]=\"APP_TYPE_WEBRTC_ANGULAR\"}(Sv||(Sv={})),function(e){e.CONNECTING=\"CONNECTING\",e.RECONNECTING=\"RECONNECTING\",e.CONNECTED=\"CONNECTED\",e.CLOSED=\"CLOSED\"}(Rv||(Rv={})),function(e){e.CONNECTION_STATE_CHANGE=\"connection-state-change\",e.STATE_CHANGE=\"state-change\",e.INSPECT_RESULT=\"inspect-result\",e.CLIENT_LOCAL_VIDEO_TRACK=\"client-local-video-track\",e.REQUEST_NEW_WORKER_URL=\"request-new-worker-url\"}(Cv||(Cv={})),function(e){e[e.CONNECT_AP=0]=\"CONNECT_AP\",e[e.AP_CONNECTED=1]=\"AP_CONNECTED\",e[e.CONNECT_WORKER_MANAGER=2]=\"CONNECT_WORKER_MANAGER\",e[e.WORKER_MANAGER_CONNECTED=3]=\"WORKER_MANAGER_CONNECTED\",e[e.GET_WORKER_MANAGER_RESPONSE=4]=\"GET_WORKER_MANAGER_RESPONSE\",e[e.CONNECT_WORKER=5]=\"CONNECT_WORKER\",e[e.WORKER_CONNECTED=6]=\"WORKER_CONNECTED\",e[e.CLOSED=7]=\"CLOSED\"}(Iv||(Iv={})),function(e){e.CALL=\"call\",e.CANDIDATE=\"candidate\",e.PUBLISH=\"publish\",e.UNPUBLISH=\"unpublish\",e.CONTROL=\"control\",e.RESTART_ICE=\"restart_ice\",e.ACK=\"ack\",e.RESPONSE=\"response\",e.JOIN=\"join\",e.CHECK=\"check\"}(vv||(vv={})),function(e){e.ABORT=\"abort\"}(yv||(yv={})),function(e){e.MUTE_LOCAL_AUDIO=\"mute_local_audio\",e.MUTE_LOCAL_VIDEO=\"mute_local_video\",e.UNMUTE_LOCAL_AUDIO=\"unmute_local_audio\",e.UNMUTE_LOCAL_VIDEO=\"unmute_local_video\"}(Av||(Av={})),function(e){e[e.SUCCESS=1]=\"SUCCESS\",e[e.FAILED=0]=\"FAILED\"}(bv||(bv={})),function(e){e.P2P_TOKEN_TIMEOUT=\"p2p_token_timeout\",e.P2P_TOKEN_CHANGED=\"p2p_token_changed\"}(wv||(wv={}));const Dv={[cI.ACCESS_POINT]:{[uI.NO_FLAG_SET]:{desc:\"flag is zero\",retry:!1},[uI.FLAG_SET_BUT_EMPTY]:{desc:\"flag is empty\",retry:!1},[uI.INVALID_FALG_SET]:{desc:\"invalid flag\",retry:!1},[uI.FLAG_SET_BUT_NO_RE]:{desc:\"flag set unilbs but no request\",retry:!1},[uI.INVALID_SERVICE_ID]:{desc:\"invalid service id\",retry:!1},[uI.NO_SERVICE_AVAILABLE]:{desc:\"no service available\",retry:!0},[uI.NO_SERVICE_AVAILABLE_P2P]:{desc:\"no unilbs p2p service available\",retry:!0},[uI.NO_SERVICE_AVAILABLE_VOICE]:{desc:\"no unilbs voice service available\",retry:!0},[uI.NO_SERVICE_AVAILABLE_WEBRTC]:{desc:\"no unilbs webrtc service available\",retry:!0},[uI.NO_SERVICE_AVAILABLE_CDS]:{desc:\"no cds service available\",retry:!0},[uI.NO_SERVICE_AVAILABLE_CDN]:{desc:\"no cdn dispatcher service available\",retry:!0},[uI.NO_SERVICE_AVAILABLE_TDS]:{desc:\"no tds service available\",retry:!0},[uI.NO_SERVICE_AVAILABLE_REPORT]:{desc:\"no unilbs report service available\",retry:!0},[uI.NO_SERVICE_AVAILABLE_APP_CENTER]:{desc:\"no app center service available\",retry:!0},[uI.NO_SERVICE_AVAILABLE_ENV0]:{desc:\"no unilbs sig env0 service available\",retry:!0},[uI.NO_SERVICE_AVAILABLE_VOET]:{desc:\"no unilbs voet service available\",retry:!0},[uI.NO_SERVICE_AVAILABLE_STRING_UID]:{desc:\"no string uid service available\",retry:!0},[uI.NO_SERVICE_AVAILABLE_WEBRTC_UNILBS]:{desc:\"no webrtc unilbs service available\",retry:!0}},[cI.UNILBS]:{[lI.INVALID_VENDOR_KEY]:{desc:\"invalid vendor key, can not find appid\",retry:!1},[lI.INVALID_CHANNEL_NAME]:{desc:\"invalid channel name\",retry:!1},[lI.INTERNAL_ERROR]:{desc:\"unilbs internal error\",retry:!1},[lI.NO_AUTHORIZED]:{desc:\"invalid token, authorized failed\",retry:!1},[lI.DYNAMIC_KEY_TIMEOUT]:{desc:\"dynamic key or token timeout\",retry:!1},[lI.NO_ACTIVE_STATUS]:{desc:\"no active status\",retry:!1},[lI.DYNAMIC_KEY_EXPIRED]:{desc:\"dynamic key expired\",retry:!1},[lI.STATIC_USE_DYNAMIC_KEY]:{desc:\"static use dynamic key\",retry:!1},[lI.DYNAMIC_USE_STATIC_KEY]:{desc:\"dynamic use static key\",retry:!1},[lI.USER_OVERLOAD]:{desc:\"amount of users over load\",retry:!1},[lI.FORBIDDEN_REGION]:{desc:\"the request is forbidden in this area\",retry:!1},[lI.CANNOT_MEET_AREA_DEMAND]:{desc:\"unable to allocate services in this area\",retry:!1}},[cI.STRING_UID_ALLOCATOR]:{[dI.IIIEGAL_APPID]:{desc:\"invalid appid\",retry:!1},[dI.IIIEGAL_UID]:{desc:\"invalid string uid\",retry:!1},[dI.INTERNAL_ERROR]:{desc:\"string uid allocator internal error\",retry:!0}}};function Pv(e){const t=Dv[Math.floor(e/1e4)];if(!t)return{desc:\"unkonw error\",retry:!1};const i=t[e%1e4];if(!i){if(Math.floor(e/1e4)===cI.ACCESS_POINT){const t=e%1e4;if(\"1\"===t.toString()[0])return{desc:e.toString(),retry:!1};if(\"2\"===t.toString()[0])return{desc:e.toString(),retry:!0}}return{desc:\"unkonw error\",retry:!1}}return i}const Lv={[hI.K_TIMESTAMP_EXPIRED]:{desc:\"K_TIMESTAMP_EXPIRED\",action:\"failed\"},[hI.K_CHANNEL_PERMISSION_INVALID]:{desc:\"K_CHANNEL_PERMISSION_INVALID\",action:\"failed\"},[hI.K_CERTIFICATE_INVALID]:{desc:\"K_CERTIFICATE_INVALID\",action:\"failed\"},[hI.K_CHANNEL_NAME_EMPTY]:{desc:\"K_CHANNEL_NAME_EMPTY\",action:\"failed\"},[hI.K_CHANNEL_NOT_FOUND]:{desc:\"K_CHANNEL_NOT_FOUND\",action:\"failed\"},[hI.K_TICKET_INVALID]:{desc:\"K_TICKET_INVALID\",action:\"failed\"},[hI.K_CHANNEL_CONFLICTED]:{desc:\"K_CHANNEL_CONFLICTED\",action:\"failed\"},[hI.K_SERVICE_NOT_READY]:{desc:\"K_SERVICE_NOT_READY\",action:\"tryNext\"},[hI.K_SERVICE_TOO_HEAVY]:{desc:\"K_SERVICE_TOO_HEAVY\",action:\"tryNext\"},[hI.K_UID_BANNED]:{desc:\"K_UID_BANNED\",action:\"failed\"},[hI.K_IP_BANNED]:{desc:\"K_IP_BANNED\",action:\"failed\"},[hI.K_AUTO_REBALANCE]:{desc:\"k_AUTO_REBALANCE\",action:\"recover\"},[hI.ERR_INVALID_VENDOR_KEY]:{desc:\"ERR_INVALID_VENDOR_KEY\",action:\"failed\"},[hI.ERR_INVALID_CHANNEL_NAME]:{desc:\"ERR_INVALID_CHANNEL_NAME\",action:\"failed\"},[hI.WARN_NO_AVAILABLE_CHANNEL]:{desc:\"WARN_NO_AVAILABLE_CHANNEL\",action:\"failed\"},[hI.WARN_LOOKUP_CHANNEL_TIMEOUT]:{desc:\"WARN_LOOKUP_CHANNEL_TIMEOUT\",action:\"tryNext\"},[hI.WARN_LOOKUP_CHANNEL_REJECTED]:{desc:\"WARN_LOOKUP_CHANNEL_REJECTED\",action:\"failed\"},[hI.WARN_OPEN_CHANNEL_TIMEOUT]:{desc:\"WARN_OPEN_CHANNEL_TIMEOUT\",action:\"tryNext\"},[hI.WARN_OPEN_CHANNEL_REJECTED]:{desc:\"WARN_OPEN_CHANNEL_REJECTED\",action:\"failed\"},[hI.WARN_REQUEST_DEFERRED]:{desc:\"WARN_REQUEST_DEFERRED\",action:\"failed\"},[hI.ERR_DYNAMIC_KEY_TIMEOUT]:{desc:\"ERR_DYNAMIC_KEY_TIMEOUT\",action:\"failed\"},[hI.ERR_NO_AUTHORIZED]:{desc:\"ERR_NO_AUTHORIZED\",action:\"failed\"},[hI.ERR_VOM_SERVICE_UNAVAILABLE]:{desc:\"ERR_VOM_SERVICE_UNAVAILABLE\",action:\"tryNext\"},[hI.ERR_NO_CHANNEL_AVAILABLE_CODE]:{desc:\"ERR_NO_CHANNEL_AVAILABLE_CODE\",action:\"failed\"},[hI.ERR_MASTER_VOCS_UNAVAILABLE]:{desc:\"ERR_MASTER_VOCS_UNAVAILABLE\",action:\"tryNext\"},[hI.ERR_INTERNAL_ERROR]:{desc:\"ERR_INTERNAL_ERROR\",action:\"tryNext\"},[hI.ERR_NO_ACTIVE_STATUS]:{desc:\"ERR_NO_ACTIVE_STATUS\",action:\"failed\"},[hI.ERR_INVALID_UID]:{desc:\"ERR_INVALID_UID\",action:\"failed\"},[hI.ERR_DYNAMIC_KEY_EXPIRED]:{desc:\"ERR_DYNAMIC_KEY_EXPIRED\",action:\"failed\"},[hI.ERR_STATIC_USE_DYANMIC_KE]:{desc:\"ERR_STATIC_USE_DYANMIC_KE\",action:\"failed\"},[hI.ERR_DYNAMIC_USE_STATIC_KE]:{desc:\"ERR_DYNAMIC_USE_STATIC_KE\",action:\"failed\"},[hI.ERR_NO_VOCS_AVAILABLE]:{desc:\"ERR_NO_VOCS_AVAILABLE\",action:\"tryNext\"},[hI.ERR_NO_VOS_AVAILABLE]:{desc:\"ERR_NO_VOS_AVAILABLE\",action:\"tryNext\"},[hI.ERR_JOIN_CHANNEL_TIMEOUT]:{desc:\"ERR_JOIN_CHANNEL_TIMEOUT\",action:\"tryNext\"},[hI.ERR_JOIN_BY_MULTI_IP]:{desc:\"ERR_JOIN_BY_MULTI_IP\",action:\"recover\"},[hI.ERR_NOT_JOINED]:{desc:\"ERR_NOT_JOINED\",action:\"failed\"},[hI.ERR_REPEAT_JOIN_REQUEST]:{desc:\"ERR_REPEAT_JOIN_REQUEST\",action:\"quit\"},[hI.ERR_REPEAT_JOIN_CHANNEL]:{desc:\"ERR_REPEAT_JOIN_CHANNEL\",action:\"quit\"},[hI.ERR_INVALID_STRINGUID]:{desc:\"ERR_INVALID_STRINGUID\",action:\"failed\"},[hI.ERR_TOO_MANY_USERS]:{desc:\"ERR_TOO_MANY_USERS\",action:\"tryNext\"},[hI.ERR_SET_CLIENT_ROLE_TIMEOUT]:{desc:\"ERR_SET_CLIENT_ROLE_TIMEOUT\",action:\"failed\"},[hI.ERR_SET_CLIENT_ROLE_NO_PERMISSION]:{desc:\"ERR_SET_CLIENT_ROLE_TIMEOUT\",action:\"failed\"},[hI.ERR_SET_CLIENT_ROLE_ALREADY_IN_USE]:{desc:\"ERR_SET_CLIENT_ROLE_ALREADY_IN_USE\",action:\"success\"},[hI.ERR_PUBLISH_REQUEST_INVALID]:{desc:\"ERR_PUBLISH_REQUEST_INVALID\",action:\"failed\"},[hI.ERR_SUBSCRIBE_REQUEST_INVALID]:{desc:\"ERR_SUBSCRIBE_REQUEST_INVALID\",action:\"failed\"},[hI.ERR_NOT_SUPPORTED_MESSAGE]:{desc:\"ERR_NOT_SUPPORTED_MESSAGE\",action:\"failed\"},[hI.ERR_ILLEAGAL_PLUGIN]:{desc:\"ERR_ILLEAGAL_PLUGIN\",action:\"failed\"},[hI.ILLEGAL_CLIENT_ROLE_LEVEL]:{desc:\"ILLEGAL_CLIENT_ROLE_LEVEL\",action:\"failed\"},[hI.ERR_REJOIN_TOKEN_INVALID]:{desc:\"ERR_REJOIN_TOKEN_INVALID\",action:\"failed\"},[hI.ERR_REJOIN_USER_NOT_JOINED]:{desc:\"ERR_REJOIN_NOT_JOINED\",action:\"failed\"},[hI.ERR_INVALID_OPTIONAL_INFO]:{desc:\"ERR_INVALID_OPTIONAL_INFO\",action:\"quit\"},[hI.ERR_TEST_RECOVER]:{desc:\"ERR_TEST_RECOVER\",action:\"recover\"},[hI.ERR_TEST_TRYNEXT]:{desc:\"ERR_TEST_TRYNEXT\",action:\"recover\"},[hI.ERR_TEST_RETRY]:{desc:\"ERR_TEST_RETRY\",action:\"recover\"},[hI.ILLEGAL_AES_PASSWORD]:{desc:\"ERR_TEST_RETRY\",action:\"failed\"},[hI.ERR_TOO_MANY_BROADCASTERS]:{desc:\"ERR_TOO_MANY_BROADCASTERS\",action:\"failed\"},[hI.ERR_TOO_MANY_SUBSCRIBERS]:{desc:\"ERR_TOO_MANY_SUBSCRIBERS\",action:\"failed\"},[hI.ERR_LICENSE_ILLEGAL]:{desc:\"ERR_LICENSE_ILLEGAL\",action:\"quit\"},[hI.ERR_LICENSE_MISSING]:{desc:\"ERR_LICENSE_MISSING\",action:\"quit\"},[hI.ERR_LICENSE_EXPIRED]:{desc:\"ERR_LICENSE_EXPIRED\",action:\"quit\"},[hI.ERR_LICENSE_MINUTES_EXCEEDED]:{desc:\"ERR_LICENSE_MINUTES_EXCEEDED\",action:\"quit\"},[hI.ERR_LICENSE_PERIOD_INVALID]:{desc:\"ERR_LICENSE_PERIOD_INVALID\",action:\"quit\"},[hI.ERR_LICENSE_MULTIPLE_SDK_SERVICE]:{desc:\"ERR_LICENSE_MULTIPLE_SDK_SERVICE\",action:\"quit\"}};function kv(e){const t=Lv[e];return t||{desc:\"UNKNOW_ERROR_\".concat(e),action:\"failed\"}}function Mv(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function Uv(e){for(var t=1;te.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING))}function Vv(e,t){if(\"string\"==typeof e)return e;const{proxy:i,host:n,port:r}=e;if(t){const e=RC(\"JOIN_GATEWAY_FALLBACK_PORT\")||443;return 443===e?\"wss://\".concat(n,\"/ws/?p=\").concat(Number(r)+150):\"wss://\".concat(n,\":\").concat(e,\"/ws/?p=\").concat(Number(r)+150)}return i?\"wss://\".concat(i,\"/ws/?h=\").concat(n,\"&p=\").concat(r):\"wss://\".concat(n,\":\").concat(r)}const Fv=/wss:\\/\\/(.+)\\/ws\\/\\?h=(.+)&p=([0-9]+)\\/?/,Bv=/wss:\\/\\/(.+)\\/ws\\/\\?p=([0-9]+)\\/?/,jv=/wss:\\/\\/(.+):([0-9]+)\\/?/,Gv=/wss:\\/\\/(.[^\\/]+)\\/?/;let Wv=0;class Hv{constructor(e,t){sh(this,\"id\",0),sh(this,\"store\",void 0),sh(this,\"recordIndex\",void 0),sh(this,\"websockets\",[]),sh(this,\"try443PortDuration\",2e3),sh(this,\"forceCloseWSDuration\",5e3),sh(this,\"try443PortTimeout\",null),sh(this,\"forceCloseTimeout\",null),sh(this,\"isTry443PortFailed\",!1),sh(this,\"isNormalPortFailed\",!1),sh(this,\"useDoubleDomain\",!1),sh(this,\"useProxy\",!1),sh(this,\"startTime\",Date.now()),this.id=++Wv,this.try443PortDuration=RC(\"JOIN_GATEWAY_TRY_443PORT_DURATION\")||2e3,this.forceCloseWSDuration=e||5e3,this.store=t}closeAllWebsockets(){this.websockets.forEach((e=>{e.onopen=null,e.onclose=null,e.onmessage=null,e.close()})),this.websockets.length=0}clearTimeout(){this.forceCloseTimeout&&clearTimeout(this.forceCloseTimeout),this.try443PortTimeout&&clearTimeout(this.try443PortTimeout)}logger(){var e;const t=Date.now()-this.startTime;for(var i=arguments.length,n=new Array(i),r=0;r{var i;return bn(i=e.host).call(i,t)}));o||(this.useDoubleDomain=!1);const a=[];if(this.useDoubleDomain)n.forEach((i=>{a.push(Vv(Uv(Uv({},e),{},{host:e.host.replace(o,i)}),t))}));else{const i=Uv({},e);if(t&&o){const e=n.find((e=>e!==o));e&&(i.host=i.host.replace(o,e))}a.push(Vv(i,t))}try{a.forEach((e=>{const t=new WebSocket(e);t.binaryType=\"arraybuffer\",s.push(t),this.logger(\"ws is connecting:\",t.url)}))}catch(n){if(this.logger(\"ws create failed\"),s.forEach((e=>e.close())),s.length=0,this.useDoubleDomain)return this.useDoubleDomain=!1,this.createWebSocket(e,t,i);if(!t&&443!==Number(e.port))return this.createWebSocket(e,!0,i);throw new LI(Hg.WS_ERR,\"init websocket failed! Error: \".concat(n.toString()))}const c=lg();this.store&&this.store.recordJoinChannelService({urls:s.map((e=>e.url)),service:\"gateway\"},this.recordIndex),s.forEach((e=>{e.onopen=()=>{this.logger(\"onopen: ws \".concat(e.url,\" open cost \").concat(Date.now()-r,\"ms\")),this.websockets.forEach((t=>{t!==e&&(t.onopen=null,t.onclose=null,t.onmessage=null,t.close(),this.logger(\"close backup websocket: \".concat(t.url)))})),this.websockets.length=0,c.resolve(e)},e.onclose=i=>{this.logger(\"onclose: ws \".concat(e.url,\" closed cost \").concat(Date.now()-r,\"ms state: \").concat(e.readyState)),t?this.isTry443PortFailed=xv(s):this.isNormalPortFailed=xv(s),this.logger(\"443: \".concat(this.useProxy?\"not try\":this.isTry443PortFailed?\"failed\":\"trying\",\" 47xx: \").concat(this.isNormalPortFailed?\"failed\":\"trying\")),(t&&this.isTry443PortFailed||!t&&(this.isTry443PortFailed||this.useProxy)&&this.isNormalPortFailed)&&(this.logger(\"onclose: all websocket is closed, \".concat(i.reason)),c.reject({code:i.code,reason:QI.A_ROUND_WS_FAILED}))},e.onmessage=t=>this.logger(\"\".concat(e.url,\" onmessage: \").concat(t.data))})),this.websockets.push(...s);return i||(()=>{const i=()=>{this.logger(\"5s timeout close un-opens, isWebsocket created: \",c.isResolved),this.websockets.forEach((e=>e.readyState!==WebSocket.OPEN&&e.close()))};if(t||this.useProxy)return this.logger(\"add 5s timeout at \".concat(t?\"try-443\":\"proxy\",\" condition\")),this.forceCloseTimeout=window.setTimeout(i,this.forceCloseWSDuration);this.try443PortTimeout=window.setTimeout((()=>{if(this.logger(\"2s timeout, isWebsocket created: \",c.isResolved),c.isResolved)return i();Sg().os===_g.MAC_OS&&wg()&&i(),this.createWebSocket(e,!0,!0).then((e=>c.resolve(e))).catch((e=>{this.isNormalPortFailed&&c.reject(e),this.logger(\"try 443 port to create ws failed\")})),this.forceCloseTimeout=window.setTimeout(i,this.forceCloseWSDuration)}),this.try443PortDuration)})(),c.promise}chooseBestWebsocket(e,t,i,n){return this.useDoubleDomain=!!t,\"string\"==typeof e&&(e=function(e){let t,i,n;return[,t,i,n]=e.match(Fv)||[],t||([,i,n]=e.match(Bv)||[]),i&&n||([,i,n]=e.match(jv)||[]),i&&n||([,i]=e.match(Gv)||[]),i||jC.warning(\"un-destructible url: \",e),{proxy:t,host:i,port:n||\"443\"}}(e)),this.recordIndex=n,this.useProxy=!!e.proxy,i&&this.useProxy&&(jC.warn(\"cannot use 443 only when use proxy\"),i=!1),this.createWebSocket(e,!!i,!1).finally((()=>this.clearTimeout()))}}function Kv(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}class Yv extends dT{get url(){return this.websocket&&this.websocket.url||null}get reconnectMode(){return this._reconnectMode}set reconnectMode(e){var t;bn(t=[\"tryNext\",\"recover\"]).call(t,e)&&this.resetReconnectCount(e),this._reconnectMode=e}get state(){return this._state}set state(e){e!==this._state&&(this._state=e,\"reconnecting\"===this._state?this.emit(SI.RECONNECTING,this.reconnectReason):\"connected\"===this._state?this.emit(SI.CONNECTED):\"closed\"===this._state?this.emit(SI.CLOSED):\"failed\"===this._state&&this.emit(SI.FAILED))}resetReconnectCount(e){jC.debug(\"websocket reset reconnect count, reason: \"+e),this.reconnectCount=0}constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]&&arguments[3],r=arguments.length>4&&void 0!==arguments[4]&&arguments[4],s=arguments.length>5?arguments[5]:void 0;super(),sh(this,\"connectionID\",0),sh(this,\"currentURLIndex\",0),sh(this,\"urls\",[]),sh(this,\"_reconnectMode\",\"tryNext\"),sh(this,\"reconnectReason\",void 0),sh(this,\"_initMutex\",new pS(\"websocket\")),sh(this,\"name\",void 0),sh(this,\"_state\",\"closed\"),sh(this,\"reconnectInterrupter\",void 0),sh(this,\"websocket\",void 0),sh(this,\"retryConfig\",void 0),sh(this,\"reconnectCount\",0),sh(this,\"forceCloseTimeout\",5e3),sh(this,\"onlineReconnectListener\",void 0),sh(this,\"useCompress\",void 0),sh(this,\"tryDoubleDomain\",!1),sh(this,\"use443PortOnly\",!1),sh(this,\"wsInflateLength\",0),sh(this,\"wsDeflateLength\",0),sh(this,\"closeEstablishingWs\",(()=>{})),sh(this,\"store\",void 0),sh(this,\"joinGatewayRecordIndex\",void 0),this.store=s,this.name=e,this.retryConfig=function(e){for(var t=1;t{e!==t&&(this.resetReconnectCount(\"network state change: \".concat(t,\" -> \").concat(e)),e===gT.ONLINE?(this.retryConfig.timeout=c,this.retryConfig.timeoutFactor=d):(this.retryConfig.timeout=o,this.retryConfig.timeoutFactor=a))}))}getConnection(){return this.websocket||void 0}async init(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;const i=await this._initMutex.lock();this.forceCloseTimeout=t,this.urls=e,this.state=\"connecting\";try{const e=lg(),t=this.urls[this.currentURLIndex];this.createWebSocketConnection(t).then(e.resolve).catch(e.reject),this.once(SI.CLOSED,(()=>{e.reject(new Kg(Hg.WS_DISCONNECT))})),this.once(SI.CONNECTED,e.resolve),await e.promise}catch(e){}finally{i()}}close(e,t){if(this.currentURLIndex=0,this.resetReconnectCount(\"close\"),this.reconnectInterrupter&&this.reconnectInterrupter(),this.websocket){this.websocket.onclose=null,this.websocket.onopen=null,this.websocket.onmessage=null;const e=this.websocket;t?setTimeout((()=>e.close()),500):e.close(),this.websocket=void 0}this.state=e?\"failed\":\"closed\",this.closeEstablishingWs&&this.closeEstablishingWs()}reconnect(e,t){if(!this.websocket)return void jC.warning(\"[\".concat(this.name,\"] can not reconnect, no websocket\"));void 0!==e&&(this.reconnectMode=e),jC.debug(\"[\".concat(this.name,\"] reconnect is triggered initiative\")),\"number\"==typeof this.joinGatewayRecordIndex&&this.store&&this.store.recordJoinChannelService({status:\"error\",errors:[new Error(t)]},this.joinGatewayRecordIndex);const i=this.websocket.onclose;this.websocket.onclose=null,this.websocket.close(),i&&i.bind(this.websocket)({code:9999,reason:t})}sendMessage(e){let t=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw new Kg(Hg.WS_ABORT,\"websocket is not ready\");try{t||(e=JSON.stringify(e)),this.websocket.send(e)}catch(e){throw new Kg(Hg.WS_ERR,\"send websocket message error\"+e.toString())}}setWsInflateData(e){this.wsDeflateLength=this.wsDeflateLength+e.originLength,this.wsInflateLength=this.wsInflateLength+e.compressedLength}getWsInflateData(){const e=this.wsInflateLength,t=this.wsDeflateLength;return this.clearWsInflateData(),{wsInflateLength:e,wsDeflateLength:t}}clearWsInflateData(){this.wsInflateLength=0,this.wsDeflateLength=0}async createWebSocketConnection(e){var t;const i=lg();this.connectionID+=1,this.joinGatewayRecordIndex=void 0;const n=e=>{var t;null===(t=this.store)||void 0===t||t.signalChannelOpen(),jC.debug(\"[\".concat(this.name,\"] websocket opened:\"),e),this.reconnectMode=\"retry\",this.state=\"connected\",this.resetReconnectCount(\"opened\"),i.resolve()},r=async e=>{var t;if(jC.debug(\"[\".concat(this.name,\"] websocket close \").concat(null===(t=this.websocket)||void 0===t?void 0:t.url,\", code: \").concat(e.code,\", reason: \").concat(e.reason,\", current mode: \").concat(this.reconnectMode)),this.reconnectCount>=this.retryConfig.maxRetryCount)i.reject(new Kg(Hg.WS_DISCONNECT,\"websocket close: \".concat(e.code))),this.close();else{\"connected\"===this.state&&(this.reconnectReason=e.reason,this.state=\"reconnecting\");const t=AT(this,SI.WILL_RECONNECT,this.reconnectMode,e.reason)||this.reconnectMode,n=await this.reconnectWithAction(t);if(\"closed\"===this.state)return void jC.debug(\"[\".concat(this.connectionID,\"] ws is closed, no need to reconnect\"));if(!n)return i.reject(new Kg(Hg.WS_DISCONNECT,\"websocket reconnect failed: \".concat(e.code))),this.close(!0);i.resolve()}},s=e=>{this.emit(SI.ON_MESSAGE,e)},o=e=>{jC.warn(\"[\".concat(this.connectionID,\"] ws open error \").concat(e))};this.websocket&&(this.websocket.onclose=null,this.websocket.close()),RC(\"GATEWAY_WSS_ADDRESS\")&&this.name.startsWith(\"gateway\")&&(e=RC(\"GATEWAY_WSS_ADDRESS\")),jC.debug(\"[\".concat(this.name,\"] start connect, url:\"),e);const a=null===(t=this.store)||void 0===t?void 0:t.recordJoinChannelService({startTs:Date.now(),status:\"pending\",service:\"gateway\"});try{var c;const t=await this.chooseBestWebsocketConnection(e);this.websocket=t,n&&n(this.websocket.url),this.websocket.onclose=r,this.websocket.onmessage=s,this.websocket.onerror=o,null===(c=this.store)||void 0===c||c.recordJoinChannelService({endTs:Date.now(),status:\"success\"},a),this.joinGatewayRecordIndex=a}catch(e){const t=\"closed\"===this.state,n=e instanceof Kg,s=n&&e.code===Hg.WS_ABORT,o=n&&e.code===Hg.WS_ERR,c=n?e.message:e&&(e.reason||e.toString());jC.warning(\"[choose-best-ws] chooseBestWebsocket error: \".concat(c)),this.store&&this.store.recordJoinChannelService({endTs:Date.now(),status:s?\"aborted\":\"error\",errors:[e]},a),t||o?(i.reject(t?new Kg(Hg.WS_DISCONNECT,\"websocket is closed: \".concat(c)):new Kg(Hg.WS_ERR,\"init websocket failed: \".concat(c))),o&&jC.error(\"[\".concat(this.name,\"] init websocket failed: \").concat(c))):r&&r(e)}return i.promise}async reconnectWithAction(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(this.reconnectCount>=this.retryConfig.maxRetryCount)return!1;if(0===this.urls.length)return!1;if(\"closed\"===this.state)return!1;jC.warning(\"[choose-best-ws] action: =>\",e),this.onlineReconnectListener||wT.isOnline||!wT.onlineWaiter||(this.onlineReconnectListener=wT.onlineWaiter.then((()=>{this.onlineReconnectListener=void 0})));let i=!0;if(this.reconnectInterrupter=()=>i=!1,t){const t=mS(this.reconnectCount,this.retryConfig);jC.debug(\"[\".concat(this.name,\"] wait \").concat(t,\"ms to reconnect websocket, mode: \").concat(e)),await cg.race([iS(t),this.onlineReconnectListener||new cg((()=>{}))])}if(\"closed\"===this._state||!i)return!1;this.reconnectCount+=1;const n=async(e,t)=>{this.emit(SI.RECONNECT_CREATE_CONNECTION,t),await this.createWebSocketConnection(e)};try{if(\"retry\"===e)this.emit(SI.RECONNECT_WAITTING_FINISH,e),await n(this.urls[this.currentURLIndex],e);else if(\"tryNext\"===e){if(this.currentURLIndex+=1,this.currentURLIndex>=this.urls.length)return this.reconnectWithAction(\"recover\",!1);jC.debug(\"[\".concat(this.name,\"] websocket url length: \").concat(this.urls.length,\" current index: \").concat(this.currentURLIndex)),this.emit(SI.RECONNECT_WAITTING_FINISH,e),await n(this.urls[this.currentURLIndex],e)}else\"recover\"===e&&(jC.debug(\"[\".concat(this.name,\"] request new urls\")),this.resetReconnectCount(\"recover mode\"),this.emit(SI.RECONNECT_WAITTING_FINISH,e),this.urls=await vT(this,SI.REQUEST_NEW_URLS),this.currentURLIndex=0,await n(this.urls[this.currentURLIndex],e))}catch(i){var r;jC.error(\"[\".concat(this.name,\"] reconnect failed \").concat(i&&i.toString()));const n=null==i||null===(r=i.data)||void 0===r?void 0:r.desc;return Array.isArray(n)&&bn(n).call(n,\"dynamic key expired\")?(this.emit(SI.ON_TOKEN_PRIVILEGE_DID_EXPIRE),!1):this.reconnectWithAction(e,t)}return!0}}class qv extends Yv{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]&&arguments[2],arguments.length>3&&void 0!==arguments[3]&&arguments[3],arguments.length>4&&void 0!==arguments[4]&&arguments[4],arguments.length>5?arguments[5]:void 0)}async chooseBestWebsocketConnection(e,t){const i=lg(),n=function(e,t){return new Hv(e,t)}(this.forceCloseTimeout,this.store);this.closeEstablishingWs=()=>{jC.debug(\"[choose-best-ws] close establishing websockets\"),n.closeAllWebsockets(),i.reject(new Kg(Hg.WS_ABORT,\"choose best websocket aborted\"))};const r=RC(\"GATEWAY_DOMAINS\");return jC.debug(\"[choose-best-ws] currentDomain: \",e,\", domains: \",r,\"total: \".concat(this.urls.length),\"current: \".concat(this.currentURLIndex+1)),n.chooseBestWebsocket(e,this.tryDoubleDomain,this.use443PortOnly,t).then(i.resolve).catch(i.reject),i.promise.finally((()=>{this.closeEstablishingWs=void 0}))}}class zv extends Yv{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]&&arguments[2],arguments.length>3&&void 0!==arguments[3]&&arguments[3],arguments.length>4&&void 0!==arguments[4]&&arguments[4],arguments.length>5?arguments[5]:void 0)}async chooseBestWebsocketConnection(e,t){return new cg(((i,n)=>{let r=!1;const s=[];this.closeEstablishingWs=()=>{jC.debug(\"[choose-best-ws] close establishing websockets\"),s.forEach((e=>{e.onclose=null,e.onopen=null,e.onmessage=null,e.close()})),n(new Kg(Hg.WS_ABORT,\"choose best websocket aborted\"))};const o=RC(\"GATEWAY_DOMAINS\");let a;const c=e.indexOf(\"?h=\"),d=o.find((t=>-1!==c?bn(e).call(e,t,c):bn(e).call(e,t)));jC.debug(\"[choose-best-ws] currentDomain: \",d,\", domains: \",o);let l=!this.tryDoubleDomain||!d;if(!l&&d){var u;const h=Date.now();try{o.forEach((t=>{const i=-1===c?e.replace(d,t):e.substr(0,c)+e.substr(c).replace(d,t),n=new WebSocket(i);n.binaryType=\"arraybuffer\",s.push(n),jC.debug(\"[choose-best-ws] ws is connecting:\",n.url)}))}catch(e){for(jC.debug(\"[choose-best-ws] ws create failed, fallback to single url\"),s.forEach((e=>e.close()));s.length;)s.pop();l=!0}null===(u=this.store)||void 0===u||u.recordJoinChannelService({urls:s.map((e=>e.url)),service:\"gateway\"},t),s.forEach((e=>{e.onopen=()=>{if(r)return;const t=Date.now()-h;jC.debug(\"[choose-best-ws] ws open cost \".concat(t,\"ms\")),s.filter((t=>t!==e)).forEach((e=>{jC.debug(\"[choose-best-ws]close backup websocket: \".concat(e.url)),e.close()})),r=!0,i(e)},e.onclose=e=>{if(a=e,r)return;s.find((e=>!(e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING)))||(jC.debug(\"[choose-best-ws] all websocket is closed\"),r=!0,n(a))},e.onmessage=t=>{jC.debug(\"[choose-best-ws]\".concat(e.url,\" onmessage: \").concat(t.data))}})),iS(this.forceCloseTimeout).then((()=>{s.forEach((e=>{e.readyState!==WebSocket.OPEN&&e.close()}))}))}if(l){var h;let r;jC.debug(\"[choose-best-ws] use single url: \",e),null===(h=this.store)||void 0===h||h.recordJoinChannelService({urls:[e],service:\"gateway\"},t);try{r=new WebSocket(e),s.push(r),r.binaryType=\"arraybuffer\"}catch(e){const t=new Kg(Hg.WS_ERR,\"init websocket failed! Error: \".concat(e.toString()));return jC.error(\"[\".concat(this.name,\"]\").concat(t)),void n(t)}r.onopen=()=>{i(r)},r.onclose=e=>{n(e)},r.onmessage=e=>{jC.debug(\"[choose-best-ws]\".concat(r.url,\" onmessage: \").concat(e.data))},iS(this.forceCloseTimeout).then((()=>{r&&r.readyState!==WebSocket.OPEN&&r.close()}))}})).then((e=>(this.closeEstablishingWs=void 0,e))).catch((e=>{throw this.closeEstablishingWs=void 0,e}))}}class Jv extends dT{get connectionState(){return this._connectionState}set connectionState(e){e!==this._connectionState&&(this._connectionState=e,e===pI.CONNECTED?this.emit(_I.WS_CONNECTED):e===pI.RECONNECTING?this.emit(_I.WS_RECONNECTING,this._websocketReconnectReason):e===pI.CLOSED&&this.emit(_I.WS_CLOSED,this._disconnectedReason))}get currentURLIndex(){return this.websocket.currentURLIndex}get url(){return this.websocket&&this.websocket.url||null}get rtt(){return this.rttRolling.mean()}constructor(e,t){super(),sh(this,\"_disconnectedReason\",void 0),sh(this,\"_websocketReconnectReason\",void 0),sh(this,\"_connectionState\",pI.CLOSED),sh(this,\"reconnectToken\",void 0),sh(this,\"websocket\",void 0),sh(this,\"openConnectionTime\",void 0),sh(this,\"clientId\",void 0),sh(this,\"lastMsgTime\",Date.now()),sh(this,\"uploadCache\",[]),sh(this,\"uploadCacheInterval\",void 0),sh(this,\"rttRolling\",new gS(5)),sh(this,\"pingpongTimer\",void 0),sh(this,\"wsInflateDataTimer\",void 0),sh(this,\"pingpongTimeoutCount\",0),sh(this,\"joinResponse\",void 0),sh(this,\"multiIpOption\",void 0),sh(this,\"initError\",void 0),sh(this,\"spec\",void 0),sh(this,\"store\",void 0),sh(this,\"onWebsocketMessage\",(e=>{if(e.data instanceof ArrayBuffer)return void this.emit(_I.ON_BINARY_DATA,e.data);const t=JSON.parse(e.data);if(this.lastMsgTime=Date.now(),Object.prototype.hasOwnProperty.call(t,\"_id\")){const e=\"res-@\".concat(t._id);this.emit(e,t._result,t._message)}else if(Object.prototype.hasOwnProperty.call(t,\"_type\")){if(this.emit(t._type,t._message),t._type===fI.ON_NOTIFICATION&&this.handleNotification(t._message),t._type===fI.ON_USER_BANNED)switch(t._message.error_code){case 14:this.close(ET.UID_BANNED);break;case 15:this.close(ET.IP_BANNED);break;case 16:this.close(ET.CHANNEL_BANNED)}if(t._type===fI.ON_USER_LICENSE_BANNED)switch(t._message.error_code){case hI.ERR_LICENSE_MISSING:this.close(ET.LICENSE_MISSING);break;case hI.ERR_LICENSE_EXPIRED:this.close(ET.LICENSE_EXPIRED);break;case hI.ERR_LICENSE_MINUTES_EXCEEDED:this.close(ET.LICENSE_MINUTES_EXCEEDED);break;case hI.ERR_LICENSE_PERIOD_INVALID:this.close(ET.LICENSE_PERIOD_INVALID);break;case hI.ERR_LICENSE_MULTIPLE_SDK_SERVICE:this.close(ET.LICENSE_MULTIPLE_SDK_SERVICE);break;case hI.ERR_LICENSE_ILLEGAL:this.close(ET.LICENSE_ILLEGAL);break;default:this.close()}}})),this.clientId=e.clientId,this.spec=e,this.store=t,this.websocket=new qv(\"gateway-\".concat(this.clientId),this.spec.retryConfig,!0,RC(\"JOIN_GATEWAY_USE_DUAL_DOMAIN\"),RC(\"JOIN_GATEWAY_USE_443PORT_ONLY\"),t),this.handleWebsocketEvents(),window.addEventListener(\"offline\",(()=>{this.connectionState===pI.CONNECTED&&this.reconnect(\"retry\",fT.OFFLINE)}))}async request(e,t,i,n){const r=nS(6,\"\"),s={_id:r,_type:e,_message:t},o=this.websocket.connectionID,a=()=>new cg(((t,i)=>{if(this.connectionState===pI.CONNECTED)return t();const n=()=>{this.off(_I.WS_CLOSED,r),t()},r=()=>{this.off(_I.WS_CONNECTED,n),i(new LI(Hg.WS_ABORT))};this.once(_I.WS_CONNECTED,n),this.once(_I.WS_CLOSED,r),e!==EI.PUBLISH&&e!==EI.PUBLISH_DATASTREAM&&e!==EI.SUBSCRIBE&&e!==EI.SUBSCRIBE_DATASTREAM&&e!==EI.UNSUBSCRIBE&&e!==EI.UNSUBSCRIBE_DATASTREAM&&e!==EI.UNPUBLISH&&e!==EI.UNPUBLISH_DATASTREAM&&e!==EI.CONTROL&&e!==EI.RESTART_ICE||this.once(_I.DISCONNECT_P2P,(()=>{i(new LI(Hg.DISCONNECT_P2P))})),e!==EI.PUBLISH&&e!==EI.RESTART_ICE||this.once(_I.ABORT_P2P_EXECUTION,(()=>{i(new LI(Hg.DISCONNECT_P2P))}))}));if(this.connectionState!==pI.CONNECTING&&this.connectionState!==pI.RECONNECTING||e===EI.JOIN||e===EI.REJOIN||await a(),this.websocket.sendMessage(s,!0),n)return;const c=new cg(((i,n)=>{let s=!1;const a=(n,r)=>{s=!0,i({isSuccess:\"success\"===n,message:r||{}}),this.off(_I.WS_CLOSED,c),this.off(_I.WS_RECONNECTING,c),this.emit(_I.REQUEST_SUCCESS,e,t)};this.once(\"res-@\".concat(r),a);const c=()=>{n(new LI(Hg.WS_ABORT,\"type: \".concat(e))),this.off(_I.WS_CLOSED,c),this.off(_I.WS_RECONNECTING,c),this.off(\"res-@\".concat(r),a)};this.once(_I.WS_CLOSED,c),this.once(_I.WS_RECONNECTING,c),iS(RC(\"SIGNAL_REQUEST_TIMEOUT\")).then((()=>{this.websocket.connectionID!==o||s||(jC.warning(\"[\".concat(this.clientId,\"] ws request timeout, type: \").concat(e)),this.emit(_I.REQUEST_TIMEOUT,e,t))}))}));let d=null;try{d=await c}catch(n){if(this.connectionState===pI.CLOSED||e===EI.LEAVE)throw new LI(Hg.WS_ABORT);return!this.spec.forceWaitGatewayResponse||i?n.throw():e===EI.JOIN||e===EI.REJOIN?null:(await a(),await this.request(e,t))}if(d.isSuccess)return d.message;const l=Number(d.message.error_code||d.message.code),u=kv(l),h=new LI(Hg.UNEXPECTED_RESPONSE,\"\".concat(u.desc,\": \").concat(d.message.error_str),{code:l,data:d.message});return\"success\"===u.action?d.message:(jC.warning(\"[\".concat(this.clientId,\"] [\").concat(this.websocket.connectionID,\"] unexpected response from type \").concat(e,\", error_code: \").concat(l,\", message: \").concat(u.desc,\", action: \").concat(u.action)),l===hI.ERR_TOO_MANY_BROADCASTERS?e===EI.JOIN||e===EI.REJOIN?(this.initError=h,this.close(),h.throw()):h.throw():\"failed\"===u.action?h.throw():\"quit\"===u.action?(this.initError=h,this.close(),h.throw()):(l===hI.ERR_JOIN_BY_MULTI_IP?(this.multiIpOption=d.message.option,jC.warning(\"[\".concat(this.clientId,\"] detect multi ip, recover\")),this.reconnect(\"recover\",fT.MULTI_IP)):this.reconnect(u.action,fT.SERVER_ERROR),e===EI.JOIN||e===EI.REJOIN?null:await this.request(e,t)))}waitMessage(e,t){return new cg((i=>{const n=r=>{(!t||t(r))&&(this.off(e,n),i(r))};this.on(e,n)}))}uploadWRTCStats(e){if(!this.store.sessionId)return void jC.warn(\"[\".concat(this.clientId,\"] no session id when upload wrtc stats\"));const t={lts:Date.now(),sid:this.store.sessionId,uid:this.store.intUid,stats:e};this.upload(mI.WRTC_STATS,t)}upload(e,t){const i={_type:e,_message:t};try{this.websocket.sendMessage(i)}catch(e){const t=RC(\"MAX_UPLOAD_CACHE\")||50;this.uploadCache.push(i),this.uploadCache.length>t&&this.uploadCache.splice(0,1),this.uploadCache.length>0&&!this.uploadCacheInterval&&(this.uploadCacheInterval=window.setInterval((()=>{if(this.connectionState!==pI.CONNECTED)return;const e=this.uploadCache.splice(0,1)[0];0===this.uploadCache.length&&(window.clearInterval(this.uploadCacheInterval),this.uploadCacheInterval=void 0),this.upload(e._type,e._message)}),RC(\"UPLOAD_CACHE_INTERVAL\")||2e3))}}send(e,t){const i={_type:e,_message:t};this.websocket.sendMessage(i)}init(e,t){return this.initError=void 0,this.multiIpOption=void 0,this.joinResponse=void 0,this.reconnectToken=void 0,this.openConnectionTime=void 0,new cg(((t,i)=>{this.once(_I.WS_CONNECTED,(()=>t(this.joinResponse))),this.once(_I.WS_CLOSED,(()=>i(this.initError||new LI(Hg.WS_ABORT)))),this.connectionState=pI.CONNECTING,this.websocket.init(e).catch(i),this.wsInflateDataTimer&&window.clearInterval(this.wsInflateDataTimer),this.wsInflateDataTimer=window.setInterval((()=>{this.handleWsInflateData()}),2e4)}))}close(e){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.wsInflateDataTimer&&(this.handleWsInflateData(),window.clearInterval(this.wsInflateDataTimer),this.wsInflateDataTimer=void 0),this.reconnectToken=void 0,this.joinResponse=void 0,this._disconnectedReason=e||ET.LEAVE,this.connectionState=pI.CLOSED,jC.debug(\"[\".concat(this.clientId,\"] \")+\"will close websocket in signal\"),this.websocket.close(),e===ET.FALLBACK&&(this.websocket.removeAllListeners(),this.websocket=new qv(\"gateway-\".concat(this.clientId),this.spec.retryConfig,!0,RC(\"JOIN_GATEWAY_USE_DUAL_DOMAIN\"),RC(\"JOIN_GATEWAY_USE_443PORT_ONLY\"),this.store),this.handleWebsocketEvents())}async join(){if(!this.joinResponse){this.emit(_I.ABORT_P2P_EXECUTION);const e=await vT(this,_I.REQUEST_JOIN_INFO),t=await this.request(EI.JOIN,e);if(!t)return this.emit(_I.REPORT_JOIN_GATEWAY,QI.TIMEOUT,this.url||\"\"),!1;this.joinResponse=t,this.emit(_I.JOIN_RESPONSE,this.joinResponse),this.reconnectToken=this.joinResponse.rejoin_token}return this.connectionState=pI.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),!0}async rejoin(){if(!this.reconnectToken)throw new LI(Hg.UNEXPECTED_ERROR,\"can not rejoin, no rejoin token\");const e=bT(this,_I.REQUEST_REJOIN_INFO);e.token=this.reconnectToken;const t=await this.request(EI.REJOIN,e);return!!t&&(this.connectionState=pI.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),t.peers&&t.peers.forEach((e=>{this.emit(fI.ON_USER_ONLINE,{uid:e.uid}),e.audio&&this.emit(fI.ON_ADD_AUDIO_STREAM,{uid:e.uid,uint_id:e.uint_id,audio:!0,ssrcId:e.audio_ssrc}),e.video&&this.emit(fI.ON_ADD_VIDEO_STREAM,{uid:e.uid,uint_id:e.uint_id,video:!0,ssrcId:e.video_ssrc}),e.audio_mute?this.emit(fI.MUTE_AUDIO,{uid:e.uid}):this.emit(fI.UNMUTE_AUDIO,{uid:e.uid}),e.video_mute?this.emit(fI.MUTE_VIDEO,{uid:e.uid}):this.emit(fI.UNMUTE_VIDEO,{uid:e.uid}),e.audio_enable_local?this.emit(fI.ENABLE_LOCAL_AUDIO,{uid:e.uid}):this.emit(fI.DISABLE_LOCAL_AUDIO,{uid:e.uid}),e.video_enable_local?this.emit(fI.ENABLE_LOCAL_VIDEO,{uid:e.uid}):this.emit(fI.DISABLE_LOCAL_VIDEO,{uid:e.uid}),e.audio||e.video||this.emit(fI.ON_REMOVE_STREAM,{uid:e.uid,uint_id:e.uint_id})})),!0)}reconnect(e,t){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.websocket.reconnect(e,t)}handleNotification(e){jC.debug(\"[\".concat(this.clientId,\"] receive notification: \"),e);const t=kv(e.code);if(\"success\"!==t.action){if(\"failed\"!==t.action)return\"quit\"===t.action?(\"ERR_REPEAT_JOIN_CHANNEL\"===t.desc&&this.close(ET.UID_BANNED),void this.close()):void this.reconnect(t.action,fT.SERVER_ERROR);jC.error(\"[\".concat(this.clientId,\"] ignore error: \"),t.desc)}}handlePingPong(){if(!this.websocket||\"connected\"!==this.websocket.state)return;this.pingpongTimeoutCount>0&&this.rttRolling.add(3e3),this.pingpongTimeoutCount+=1;const e=RC(\"PING_PONG_TIME_OUT\"),t=Date.now();this.pingpongTimeoutCount>=e&&(jC.warning(\"[\".concat(this.clientId,\"] PING-PONG Timeout. Last Socket Message: \").concat(t-this.lastMsgTime,\"ms\")),t-this.lastMsgTime>RC(\"WEBSOCKET_TIMEOUT_MIN\"))?this.reconnect(\"retry\",fT.TIMEOUT):this.request(EI.PING,void 0,!0).then((()=>{this.pingpongTimeoutCount=0;const e=Date.now()-t;this.rttRolling.add(e),RC(\"REPORT_STATS\")&&this.send(EI.PING_BACK,{pingpongElapse:e})})).catch((e=>{}))}handleWsInflateData(){const{wsInflateLength:e,wsDeflateLength:t}=this.websocket.getWsInflateData();0!==e&&0!==t&&this.upload(mI.WS_INFLATE_DATA_LENGTH,{ws_deflate_length:t,ws_inflate_length:e})}handleWebsocketEvents(){this.websocket.on(SI.RECONNECT_WAITTING_FINISH,(e=>{this.emit(_I.WS_RECONNECT_WAITTING_FINISH,e)})),this.websocket.on(SI.RECONNECT_CREATE_CONNECTION,(e=>{this.emit(_I.WS_RECONNECT_CREATE_CONNECTION,e)})),this.websocket.on(SI.ON_MESSAGE,this.onWebsocketMessage),this.websocket.on(SI.CLOSED,(()=>{this.connectionState=pI.CLOSED})),this.websocket.on(SI.FAILED,(()=>{this._disconnectedReason=ET.NETWORK_ERROR,this.connectionState=pI.CLOSED})),this.websocket.on(SI.RECONNECTING,(e=>{this._websocketReconnectReason=e,this.joinResponse=void 0,this.connectionState===pI.CONNECTED?this.connectionState=pI.RECONNECTING:this.connectionState=pI.CONNECTING})),this.websocket.on(SI.WILL_RECONNECT,((e,t,i)=>{const n=bT(this,_I.IS_P2P_DISCONNECTED),r=n||\"retry\"!==e;n&&\"retry\"===e&&(jC.debug(\"\".concat(this.clientId,\" reconnect mode is retry, but p2p lost, change to tryNext\")),e=\"tryNext\",t=QI.P2P_DISCONNECTED),r&&(jC.debug(\"\".concat(this.clientId,\" will renewSession, reconnect mode: \").concat(e)),this.emit(_I.REPORT_JOIN_GATEWAY,t||QI.UNKNOWN_REASON,this.url||\"\"),this.reconnectToken=void 0,this.emit(_I.NEED_RENEW_SESSION),this.emit(_I.DISCONNECT_P2P)),i(e)})),this.websocket.on(SI.CONNECTED,(()=>{this.openConnectionTime=Date.now(),this.reconnectToken?this.rejoin().catch((e=>{jC.warning(\"[\".concat(this.clientId,\"] rejoin failed \").concat(e)),this.reconnect(\"tryNext\",fT.SERVER_ERROR)})):this.join().catch((e=>{if(this.emit(_I.REPORT_JOIN_GATEWAY,e.message||e.code||QI.UNKNOWN_REASON,this.url||\"\"),e instanceof LI&&e.code===Hg.UNEXPECTED_RESPONSE&&e.data.code===hI.ERR_NO_AUTHORIZED)return jC.warning(\"[\".concat(this.clientId,\"] reconnect no authorized, recover\")),void this.reconnect(\"recover\",fT.SERVER_ERROR);jC.error(\"[\".concat(this.clientId,\"] join gateway request failed\"),e.toString()),this.spec.forceWaitGatewayResponse?this.reconnect(\"tryNext\",fT.SERVER_ERROR):(this.initError=e,this.close())}))})),this.websocket.on(SI.REQUEST_NEW_URLS,((e,t)=>{vT(this,_I.REQUEST_RECOVER,this.multiIpOption).then(e).catch(t)})),this.websocket.on(SI.ON_TOKEN_PRIVILEGE_DID_EXPIRE,(()=>{this.emit(fI.ON_TOKEN_PRIVILEGE_DID_EXPIRE)}))}}var Xv=\"\\t\\n\\v\\f\\r \u00A0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\\u2028\\u2029\\ufeff\",Qv=J,Zv=pn,$v=Xv,ey=d(\"\".replace),ty=RegExp(\"^[\"+$v+\"]+\"),iy=RegExp(\"(^|[^\"+$v+\"])[\"+$v+\"]+$\"),ny=function(e){return function(t){var i=Zv(Qv(t));return 1&e&&(i=ey(i,ty,\"\")),2&e&&(i=ey(i,iy,\"$1\")),i}},ry={start:ny(1),end:ny(2),trim:ny(3)},sy=zd.PROPER,oy=n,ay=Xv,cy=ry.trim;wi({target:\"String\",proto:!0,forced:function(e){return oy((function(){return!!ay[e]()||\"\u200B\u0085\u180E\"!==\"\u200B\u0085\u180E\"[e]()||sy&&ay[e].name!==e}))}(\"trim\")},{trim:function(){return cy(this)}});var dy,ly,uy=zi(\"String\").trim,hy=l,py=uy,_y=String.prototype,Ey=i((function(e){var t=e.trim;return\"string\"==typeof e||e===_y||hy(_y,e)&&t===_y.trim?py:t}));function my(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function fy(e){for(var t=1;t{let{ip:t,port:i}=e;return{address:\"\".concat(t,\":\").concat(i)}}));const i=RC(\"GATEWAY_DOMAINS\");let n=i[1]&&bn(t).call(t,i[1])?1:0;return e.map((e=>{let{domain_prefix:t,port:r,ip:s}=e;if(t)return{address:\"\".concat(t,\".\").concat(i[n++%i.length],\":\").concat(r)};const o=/^[\\.\\:\\d]+$/.test(s),a=o?\"\".concat(s.replace(/[^\\d]/g,\"-\"),\".\").concat(i[n++%i.length],\":\").concat(r):\"\".concat(s,\":\").concat(r);return o||jC.info(\"Unidentified as ip: \".concat(s,\", use as host\")),{ip:s,port:r,address:a}}))}(e.addresses,t),n=Array.isArray(e.detail)&&e.detail[18];if(n&&\"string\"==typeof n){const e=n.split(\";\");for(let t=0;t=0&&e<.17?1:e>=.17&&e<.36?2:e>=.36&&e<.59?3:e>=.59&&e<=1?4:e>1?5:0}function Iy(e,t){let i,n,r;switch(t){case dy.CHOOSE_SERVER:n=4096,r=\"choose server\";break;case dy.CLOUD_PROXY:n=1048576,r=\"proxy\";break;case dy.CLOUD_PROXY_5:n=4194304,r=\"proxy5\";break;case dy.CLOUD_PROXY_FALLBACK:n=4194310,r=\"proxy fallback\";break;default:throw new LI(Hg.UNEXPECTED_ERROR,\"multi unlibs response transformer get unknown service id\",{csIp:e.detail&&e.detail[502],retry:!1})}if(e.response_body.forEach((t=>{t.buffer&&t.buffer.flag===n&&(i={code:t.buffer.code,addresses:(t.buffer.edges_services||[]).map((e=>fy(fy({},e),{},{ticket:t.buffer.cert}))),server_ts:e.enter_ts,uid:t.buffer.uid,cid:t.buffer.cid,cname:t.buffer.cname,detail:fy(fy({},t.buffer.detail),e.detail),flag:t.buffer.flag,opid:e.opid,cert:t.buffer.cert})})),!i)throw new LI(Hg.MULTI_UNILBS_RESPONSE_ERROR,\"cannot parse response \".concat(r,\" from multi unilbs response\"),{csIp:e.detail&&e.detail[502]});return i}async function vy(e,t){return await cg.all(e.addresses.map((async e=>({address:gy(e.ip),tcpport:e.port,udpport:e.port,username:t&&RC(\"ENCRYPT_PROXY_USERNAME_AND_PSW\")&&window.isSecureContext?t.toString():iI.username,password:t&&RC(\"ENCRYPT_PROXY_USERNAME_AND_PSW\")&&window.isSecureContext?await cT(t.toString()):iI.password}))))}function yy(e,t){const i=t._videoHeight||t.getMediaStreamTrack(!0).getSettings().height;return i?Math.max(i/Sy(e.height),1):(jC.warning(\"can't get ori-track's height, default scale down 4 times for low stream\"),4)}function Ay(e){let{candidateType:t,relayProtocol:i,type:n,address:r,port:s,protocol:o}=e;return\"local-candidate\"===n?{candidateType:t,relayProtocol:i,protocol:o}:{candidateType:t,relayProtocol:i,address:r,port:s,protocol:o}}function by(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}!function(e){e[e.CHOOSE_SERVER=11]=\"CHOOSE_SERVER\",e[e.CLOUD_PROXY=18]=\"CLOUD_PROXY\",e[e.CLOUD_PROXY_5=20]=\"CLOUD_PROXY_5\",e[e.CLOUD_PROXY_FALLBACK=26]=\"CLOUD_PROXY_FALLBACK\"}(dy||(dy={}));class wy extends dT{get url(){return this._url?this._url:null}get reconnectMode(){return this._reconnectMode}set reconnectMode(e){var t;bn(t=[\"tryNext\",\"recover\"]).call(t,e)&&this.resetReconnectCount(e),this._reconnectMode=e}get state(){return this._state}set state(e){e!==this._state&&(this._state=e,\"reconnecting\"===this._state?this.emit(gv.RECONNECTING,this.reconnectReason):\"connected\"===this._state?this.emit(gv.CONNECTED):\"closed\"===this._state?this.emit(gv.CLOSED):\"failed\"===this._state&&this.emit(gv.FAILED))}constructor(e,t,i,n){super(),sh(this,\"connectionID\",0),sh(this,\"currentURLIndex\",0),sh(this,\"reconnectReason\",void 0),sh(this,\"_reconnectMode\",\"tryNext\"),sh(this,\"_name\",void 0),sh(this,\"_state\",\"closed\"),sh(this,\"_retryConfig\",void 0),sh(this,\"_reconnectCount\",0),sh(this,\"_forceCloseTimeout\",5e3),sh(this,\"_onlineReconnectListener\",void 0),sh(this,\"_closeEstablishingTransmitter\",(()=>{})),sh(this,\"_store\",void 0),sh(this,\"_joinChannelServiceRecordIndex\",void 0),sh(this,\"_useCompress\",void 0),sh(this,\"_inflateLength\",0),sh(this,\"_deflateLength\",0),this._store=n,this._name=e,this._retryConfig=function(e){for(var t=1;te.close()),500):e.close(),this._transmitter=void 0}this.state=e?\"failed\":\"closed\",this._closeEstablishingTransmitter&&this._closeEstablishingTransmitter()}reconnect(e,t){if(!this._transmitter)return void jC.warning(\"[\".concat(this._name,\"] can not reconnect, no websocket\"));var i;(void 0!==e&&(this.reconnectMode=e),jC.debug(\"[\".concat(this._name,\"] reconnect is triggered initiative\")),\"number\"==typeof this._joinChannelServiceRecordIndex)&&(null===(i=this._store)||void 0===i||i.recordJoinChannelService({status:\"error\",errors:[new Error(t)]},this._joinChannelServiceRecordIndex));const n=this._transmitter.onclose;this._transmitter.onclose=null,this._transmitter.close(),n&&n.bind(this._transmitter)({code:9999,reason:t})}getInflateData(){const e=this._inflateLength,t=this._deflateLength;return this.clearInflateData(),{inflateLength:e,deflateLength:t}}setInflateData(e){this._deflateLength=this._deflateLength+e.originLength,this._inflateLength=this._inflateLength+e.compressedLength}clearInflateData(){this._inflateLength=0,this._deflateLength=0}}!function(e){e[e.Default=0]=\"Default\",e[e.Ack=1]=\"Ack\"}(ly||(ly={}));class Oy{constructor(e,t,i){sh(this,\"version\",1),sh(this,\"initialRTO\",void 0),sh(this,\"maxBatchAckCount\",void 0),sh(this,\"maxRTO\",void 0),sh(this,\"initialRTT\",void 0),sh(this,\"ID\",void 0),sh(this,\"rtt\",void 0),sh(this,\"packetNumber\",1),sh(this,\"rtoRatioMap\",new Map),sh(this,\"timeoutMap\",new Map),sh(this,\"unorderedPacketQueue\",[]),sh(this,\"batchAckPacketQueue\",[]),sh(this,\"lastOrderedPacketNumber\",0),sh(this,\"batchAckTimer\",void 0),sh(this,\"sendImpl\",void 0),sh(this,\"receiveImpl\",void 0),this.sendImpl=e,this.receiveImpl=t,this.ID=nS(7,\"transmitter-\"),this.initialRTO=void 0!==(null==i?void 0:i.initialRTO)?i.initialRTO:RC(\"TRANSMITTER_INITIAL_RTO\"),this.initialRTT=void 0!==(null==i?void 0:i.initialRTT)?i.initialRTT:RC(\"TRANSMITTER_INITIAL_RTT\"),this.rtt=void 0!==(null==i?void 0:i.initialRTT)?i.initialRTT:RC(\"TRANSMITTER_INITIAL_RTT\"),this.maxBatchAckCount=void 0!==(null==i?void 0:i.maxBatchAckCount)?i.maxBatchAckCount:RC(\"TRANSMITTER_MAX_BATCH_ACK_COUNT\"),this.maxRTO=void 0!==(null==i?void 0:i.maxRTO)?i.maxRTO:RC(\"TRANSMITTER_MAX_RTO\")}packetize(e,t){return{type:ly.Default,version:this.version,packetNumber:t,payload:e}}serialize(e){switch(e.type){case ly.Default:{let t;if(\"string\"==typeof e.payload){t=(new TextEncoder).encode(e.payload)}else t=e.payload;const i=new ArrayBuffer(t.length+15),n=new DataView(i);n.setUint16(0,e.version),n.setUint8(2,e.type),n.setUint32(3,e.packetNumber),tT(n,7,BigInt(e.sendTs));return new Uint8Array(n.buffer).set(t,15),i}case ly.Ack:{const t=new ArrayBuffer(16),i=new DataView(t);return i.setUint16(0,e.version),i.setUint8(2,e.type),i.setUint32(3,e.maxAckPacketNumber),i.setUint8(7,e.shift),tT(i,8,BigInt(e.ackSendTs)),t}}}deserialize(e){const t=new DataView(e),i=t.getUint16(0),n=t.getUint8(2);switch(n){case ly.Default:{const r=t.getUint32(3),s=eT(t,7),o=e.slice(15),a=(new TextDecoder).decode(o);return{version:i,type:n,packetNumber:r,sendTs:Number(s),payload:a}}case ly.Ack:{const e=t.getUint32(3),r=t.getUint8(7),s=eT(t,8);return{version:i,type:n,maxAckPacketNumber:e,shift:r,ackSendTs:Number(s)}}default:throw jC.error(\"[\".concat(this.ID,\"] Unrecognized packet type \").concat(n)),new Error(\"Unrecognized packet type \".concat(n))}}sendMessage(e){const t=this.packetize(e,this.packetNumber);this.packetNumber=4294967295===this.packetNumber?1:this.packetNumber+1;const i=this.calculateRTO(t),n=window.setTimeout((()=>{this.resendMessage(t)}),i);this.timeoutMap.set(t.packetNumber,n),this.sendPacket(t)}onData(e){const t=this.deserialize(e);t.type===ly.Default?this.ack(t):t.type===ly.Ack&&(this.updateRTT(t,Math.round(performance.now())),this.clearRTO(t))}close(){this.rtt=this.initialRTT,this.packetNumber=1,Array.from(this.timeoutMap.entries()).forEach((e=>{let[t,i]=e;window.clearTimeout(i)})),this.timeoutMap=new Map,this.rtoRatioMap=new Map,this.unorderedPacketQueue=[],this.batchAckPacketQueue=[],this.lastOrderedPacketNumber=0,void 0!==this.batchAckTimer&&window.clearTimeout(this.batchAckTimer)}resendMessage(e){const t=this.calculateRTO(e),i=window.setTimeout((()=>{this.resendMessage(e)}),t);this.timeoutMap.set(e.packetNumber,i),this.sendPacket(e)}calculateRTO(e){const t=this.rtoRatioMap.get(e.packetNumber);if(void 0===t)return this.rtoRatioMap.set(e.packetNumber,1),this.initialRTO;{const i=9*this.rtt/8*t;return this.rtoRatioMap.set(e.packetNumber,t+1),i>this.maxRTO?this.maxRTO:i}}updateRTT(e,t){const i=e.ackSendTs;this.rtt=this.rtt*(7/8)+(t-i-this.rtt)/8}ack(e){if(e.packetNumber===this.lastOrderedPacketNumber+1)for(this.batchAckPacketQueue.length>=this.maxBatchAckCount&&this.batchAck(),this.batchAckTimer?this.batchAckPacketQueue.push(e):(this.batchAckPacketQueue.push(e),this.batchAckTimer=window.setTimeout((()=>{this.batchAck()}),this.rtt/8)),this.lastOrderedPacketNumber+=1,this.receiveImpl(e.payload);;){const e=this.unorderedPacketQueue[0];if(!e){this.unorderedPacketQueue.shift();break}this.batchAckTimer&&this.batchAck(),this.receiveImpl(e.payload),this.unorderedPacketQueue.shift(),this.lastOrderedPacketNumber+=1}else if(e.packetNumber<=this.lastOrderedPacketNumber){const t={ackSendTs:e.sendTs,maxAckPacketNumber:e.packetNumber,shift:0,type:ly.Ack,version:this.version};this.sendPacket(t)}else if(e.packetNumber>this.lastOrderedPacketNumber){this.unorderedPacketQueue[e.packetNumber-this.lastOrderedPacketNumber-2]=e;const t={ackSendTs:e.sendTs,maxAckPacketNumber:e.packetNumber,shift:0,type:ly.Ack,version:this.version};this.sendPacket(t)}}batchAck(){window.clearTimeout(this.batchAckTimer),this.batchAckTimer=void 0;const e={ackSendTs:this.batchAckPacketQueue[this.batchAckPacketQueue.length-1].sendTs,maxAckPacketNumber:this.batchAckPacketQueue[this.batchAckPacketQueue.length-1].packetNumber,shift:this.batchAckPacketQueue.length-1,type:ly.Ack,version:this.version};this.sendPacket(e),this.batchAckPacketQueue=[]}sendPacket(e){e.type===ly.Default&&(e.sendTs=Math.round(performance.now()));const t=this.serialize(e);this.sendImpl(t)}clearRTO(e){for(let t=e.maxAckPacketNumber-e.shift;t<=e.maxAckPacketNumber;t++){const e=this.timeoutMap.get(t);void 0!==e&&window.clearTimeout(e),this.timeoutMap.delete(t),this.rtoRatioMap.delete(t)}}}class Ny extends wy{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]&&arguments[2],arguments.length>3?arguments[3]:void 0),sh(this,\"_initMutex\",void 0),sh(this,\"_reconnectInterrupter\",void 0),sh(this,\"_url\",void 0),sh(this,\"_transmitter\",void 0),sh(this,\"_addresses\",void 0),sh(this,\"_reliableTransmission\",void 0),this._initMutex=new pS(\"datachannel\");const{timeout:i,timeoutFactor:n}=t,r=Math.max(300,Math.floor(3*i/5)),s=Math.max(1.2,Math.floor(8*n)/10);gT.ONLINE&&(this._retryConfig.timeout=r,this._retryConfig.timeoutFactor=s),wT.on(TT.NETWORK_STATE_CHANGE,((e,t)=>{e!==t&&(this.resetReconnectCount(\"network state change: \".concat(t,\" -> \").concat(e)),e===gT.ONLINE?(this._retryConfig.timeout=r,this._retryConfig.timeoutFactor=s):(this._retryConfig.timeout=i,this._retryConfig.timeoutFactor=n))}))}getConnection(){if(this._reliableTransmission)return this._reliableTransmission}async init(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;this._forceCloseTimeout=t;const i=(t,i)=>{this._addresses=e,this.currentURLIndex=this._addresses.findIndex((e=>e.fingerprint||RC(\"FINGERPRINT\")));const n=this._addresses[this.currentURLIndex];this.state=\"connecting\",this.createTransmitterConnection(n).then(t).catch(i),this.once(gv.CLOSED,(()=>i(new LI(Hg.WS_DISCONNECT)))),this.once(gv.CONNECTED,(()=>t()))};return this._initMutex.lock().then((e=>new cg(((e,t)=>{i(e,t)})).then((()=>{e()})).catch((()=>{e()}))))}sendMessage(e){let t=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!this._transmitter||!this._reliableTransmission)throw new LI(Hg.WS_ABORT,\"datachannel is not ready\");try{t||(e=JSON.stringify(e)),this._reliableTransmission.sendMessage(e)}catch(e){throw new LI(Hg.WS_ERR,\"send datachannel signal message error\"+e.toString())}}unbindDcCloseEventListener(){this._transmitter&&(this._transmitter.onclose=null)}sendMessageWithJSON(e){const t=JSON.stringify(e);return{compressed:t,compressedLength:t.length,origin:e}}sendMessageWithUint8Array(e){return{compressed:e,compressedLength:e.byteLength,origin:e}}createTransmitterConnection(e){return this.connectionID+=1,this._joinChannelServiceRecordIndex=void 0,this._url=\"dc://\".concat(e.ip,\":\").concat(e.port),new cg(((t,i)=>{var n;const r=()=>{jC.debug(\"[\".concat(this._name,\"] datachannel opened:\"),this._url),this.reconnectMode=\"retry\",this.state=\"connected\",this.resetReconnectCount(\"opened\"),t()},s=async e=>{var n;if(null===(n=this._closeEstablishingTransmitter)||void 0===n||n.call(this),jC.debug(\"[\".concat(this._name,\"] datachannel close \").concat(this._url,\", code: \").concat(e.code,\", reason: \").concat(e.reason,\", current mode: \").concat(this.reconnectMode)),this._reconnectCount{var t;null===(t=this._reliableTransmission)||void 0===t||t.onData(e.data)};this._transmitter&&(this._transmitter.onclose=null,this._transmitter.close()),this._reliableTransmission&&(this._reliableTransmission.close(),this._reliableTransmission=void 0),jC.debug(\"[\".concat(this._name,\"] start connect, address: \").concat(JSON.stringify(e)));const a=null===(n=this._store)||void 0===n?void 0:n.recordJoinChannelService({startTs:Date.now(),status:\"pending\",service:\"gateway\"}),c=Date.now();vT(this,gv.TO_CONNECT_DATACHANNEL,e).then((e=>{var t,i;if(!e)throw new Error(\"transmissonInfo not exist yet\");const{transmitter:n,close:d}=e;this._transmitter=n,null===(t=this._store)||void 0===t||t.signalChannelOpen();const l=Date.now()-c;jC.debug(\"[choose dc] dc open cost \".concat(l,\"ms\"));this._reliableTransmission=new Oy((e=>{var t;this._transmitter&&\"open\"===this._transmitter.readyState&&(null===(t=this._transmitter)||void 0===t||t.send(e))}),(e=>{\"string\"==typeof e&&this.emit(gv.ON_MESSAGE,e)})),this._closeEstablishingTransmitter=()=>{var e;null===(e=this._reliableTransmission)||void 0===e||e.close(),this._reliableTransmission=void 0,d()},r&&r(),n.onclose=s,n.onmessage=o,null===(i=this._store)||void 0===i||i.recordJoinChannelService({endTs:Date.now(),status:\"success\"},a),this._joinChannelServiceRecordIndex=a})).catch((e=>{var t;if(null===(t=this._store)||void 0===t||t.recordJoinChannelService({endTs:Date.now(),status:e instanceof LI&&e.code===Hg.WS_ABORT?\"aborted\":\"error\",errors:[e]},a),\"closed\"!==this.state){if(e instanceof LI&&e.code===Hg.WS_ERR){const t=new LI(Hg.WS_ERR,\"init datachannel failed! Error: \".concat(e.toString()));return jC.error(\"[\".concat(this._name,\"]\").concat(t)),void i(t)}s&&s(e)}else i(new LI(Hg.WS_DISCONNECT,\"datachannel is closed: \".concat(e.toString())))}))}))}async reconnectWithAction(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(this._reconnectCount>=this._retryConfig.maxRetryCount)return!1;if(!this._addresses)return!1;if(\"closed\"===this.state)return!1;this._onlineReconnectListener||wT.networkState!==gT.OFFLINE||(this._onlineReconnectListener=wT.onlineWaiter&&wT.onlineWaiter.then((()=>{this._onlineReconnectListener=void 0})));let i=!0;if(this._reconnectInterrupter=()=>{i=!1},t){const t=mS(this._reconnectCount,this._retryConfig);jC.debug(\"[\".concat(this._name,\"] wait \").concat(t,\"ms to reconnect datachannel, mode: \").concat(e)),await cg.race([iS(t),this._onlineReconnectListener||new cg((()=>{}))])}if(\"closed\"===this.state||!i)return!1;this._reconnectCount+=1;const n=async(e,t)=>{this.emit(gv.RECONNECT_CREATE_CONNECTION,t),await this.createTransmitterConnection(e)};try{if(\"retry\"===e){const t=this._addresses[this.currentURLIndex];this.emit(gv.RECONNECT_WAITTING_FINISH,e),await n(t,e)}else if(\"tryNext\"===e){this.currentURLIndex+=1;for(let e=this.currentURLIndex;e=this._addresses.length)return jC.debug(\"[\".concat(this._name,\"] the available addresses are exhausted, change to recover\")),await this.reconnectWithAction(\"recover\",!1);jC.debug(\"[\".concat(this._name,\"] datachannel url length: \").concat(this._addresses.length,\" current index: \").concat(this.currentURLIndex));const t=this._addresses[this.currentURLIndex];this.emit(gv.RECONNECT_WAITTING_FINISH,e),await n(t,e)}else\"recover\"===e&&(jC.debug(\"[\".concat(this._name,\"] start to failback to websocket\")),this.resetReconnectCount(\"recover mode\"),this.emit(gv.RECONNECT_WAITTING_FINISH,e),this.emit(gv.FAILBACK));return!0}catch(i){var r,s;return jC.error(\"[\".concat(this._name,\"] reconnect failed\"),i.toString()),null!=i&&null!==(r=i.data)&&void 0!==r&&r.desc&&Array.isArray(i.data.desc)&&i.data.desc.length&&bn(s=i.data.desc).call(s,\"dynamic key expired\")?(this.emit(gv.ON_TOKEN_PRIVILEGE_DID_EXPIRE),!1):await this.reconnectWithAction(e,t)}}}class Dy extends dT{get connectionState(){return this._connectionState}set connectionState(e){e!==this._connectionState&&(this._connectionState=e,e===pI.CONNECTED?this.emit(_I.WS_CONNECTED):e===pI.RECONNECTING?this.emit(_I.WS_RECONNECTING,this._websocketReconnectReason):e===pI.CLOSED&&this.emit(_I.WS_CLOSED,this._disconnectedReason))}get currentURLIndex(){return this.websocket.currentURLIndex}get url(){return this.websocket?this.websocket.url:null}get rtt(){return this.rttRolling.mean()}constructor(e,t){super(),sh(this,\"_disconnectedReason\",void 0),sh(this,\"_websocketReconnectReason\",void 0),sh(this,\"_connectionState\",pI.CLOSED),sh(this,\"reconnectToken\",void 0),sh(this,\"websocket\",void 0),sh(this,\"openConnectionTime\",void 0),sh(this,\"clientId\",void 0),sh(this,\"lastMsgTime\",Date.now()),sh(this,\"uploadCache\",[]),sh(this,\"uploadCacheInterval\",void 0),sh(this,\"rttRolling\",new gS(5)),sh(this,\"pingpongTimer\",void 0),sh(this,\"inflateDataTimer\",void 0),sh(this,\"pingpongTimeoutCount\",0),sh(this,\"joinResponse\",void 0),sh(this,\"multiIpOption\",void 0),sh(this,\"initError\",void 0),sh(this,\"spec\",void 0),sh(this,\"store\",void 0),sh(this,\"onWebsocketMessage\",(e=>{if(e instanceof ArrayBuffer)return void this.emit(_I.ON_BINARY_DATA,e);const t=JSON.parse(e);if(this.lastMsgTime=Date.now(),Object.prototype.hasOwnProperty.call(t,\"_id\")){const e=\"res-@\".concat(t._id);this.emit(e,t._result,t._message)}else if(Object.prototype.hasOwnProperty.call(t,\"_type\")&&(this.emit(t._type,t._message),t._type===fI.ON_NOTIFICATION&&this.handleNotification(t._message),t._type===fI.ON_USER_BANNED))switch(t._message.error_code){case 14:this.close(ET.UID_BANNED);break;case 15:this.close(ET.IP_BANNED);break;case 16:this.close(ET.CHANNEL_BANNED)}})),this.clientId=e.clientId,this.spec=e,this.store=t,this.websocket=new Ny(\"gateway-\".concat(this.clientId),this.spec.retryConfig,!0,t),this.handleWebsocketEvents(),window.addEventListener(\"offline\",(()=>{this.connectionState===pI.CONNECTED&&this.reconnect(\"retry\",fv.OFFLINE)}))}async request(e,t,i,n){const r=nS(6,\"\"),s={_id:r,_type:e,_message:t},o=this.websocket.connectionID,a=()=>new cg(((t,i)=>{if(this.connectionState===pI.CONNECTED)return t();const n=()=>{this.off(_I.WS_CLOSED,r),t()},r=()=>{this.off(_I.WS_CONNECTED,n),i(new LI(Hg.WS_ABORT))};this.once(_I.WS_CONNECTED,n),this.once(_I.WS_CLOSED,r),e!==EI.PUBLISH&&e!==EI.SUBSCRIBE&&e!==EI.UNSUBSCRIBE&&e!==EI.UNPUBLISH&&e!==EI.CONTROL&&e!==EI.RESTART_ICE||this.once(_I.DISCONNECT_P2P,(()=>{i(new LI(Hg.DISCONNECT_P2P))})),e!==EI.PUBLISH&&e!==EI.RESTART_ICE||this.once(_I.ABORT_P2P_EXECUTION,(()=>{i(new LI(Hg.DISCONNECT_P2P))}))}));if(this.connectionState!==pI.CONNECTING&&this.connectionState!==pI.RECONNECTING||e===EI.JOIN||e===EI.REJOIN||await a(),e===EI.LEAVE&&(this.websocket.unbindDcCloseEventListener(),n=!0),this.websocket.sendMessage(s,!0,!1),n)return;const c=new cg(((i,n)=>{let s=!1;const a=(n,r)=>{s=!0,i({isSuccess:\"success\"===n,message:r||{}}),this.off(_I.WS_CLOSED,c),this.off(_I.WS_RECONNECTING,c),this.emit(_I.REQUEST_SUCCESS,e,t)};this.once(\"res-@\".concat(r),a);const c=()=>{n(new LI(Hg.WS_ABORT,\"type: \".concat(e))),this.off(_I.WS_CLOSED,c),this.off(_I.WS_RECONNECTING,c),this.off(\"res-@\".concat(r),a)};this.once(_I.WS_CLOSED,c),this.once(_I.WS_RECONNECTING,c),iS(RC(\"SIGNAL_REQUEST_TIMEOUT\")).then((()=>{this.websocket.connectionID!==o||s||(jC.warning(\"dc request timeout, type: \".concat(e)),this.emit(_I.REQUEST_TIMEOUT,e,t))}))}));let d=null;try{d=await c}catch(n){if(this.connectionState===pI.CLOSED||e===EI.LEAVE)throw new LI(Hg.WS_ABORT);return!this.spec.forceWaitGatewayResponse||i?n.throw():e===EI.JOIN||e===EI.REJOIN?null:(await a(),await this.request(e,t))}if(d.isSuccess)return d.message;const l=Number(d.message.error_code||d.message.code),u=kv(l),h=new LI(Hg.UNEXPECTED_RESPONSE,\"\".concat(u.desc,\": \").concat(d.message.error_str),{code:l,data:d.message});return\"success\"===u.action?d.message:(jC.warning(\"[\".concat(this.websocket.connectionID,\"] unexpected response from type \").concat(e,\", error_code: \").concat(l,\", message: \").concat(u.desc,\", action: \").concat(u.action)),l===hI.ERR_TOO_MANY_BROADCASTERS?e===EI.JOIN||e===EI.REJOIN?(this.initError=h,this.close(),h.throw()):h.throw():\"failed\"===u.action?h.throw():\"quit\"===u.action?(this.initError=h,this.close(),h.throw()):(l===hI.ERR_JOIN_BY_MULTI_IP?(this.multiIpOption=d.message.option,jC.warning(\"[\".concat(this.clientId,\"] detect multi ip, recover\")),this.reconnect(\"recover\",fv.MULTI_IP)):this.reconnect(u.action,fv.SERVER_ERROR),e===EI.JOIN||e===EI.REJOIN?null:await this.request(e,t)))}waitMessage(e,t){return new cg((i=>{const n=r=>{(!t||t(r))&&(this.off(e,n),i(r))};this.on(e,n)}))}uploadWRTCStats(e){if(!this.store.sessionId)return void jC.warn(\"[\".concat(this.clientId,\"] no session id when upload wrtc stats\"));const t={lts:Date.now(),sid:this.store.sessionId,uid:this.store.intUid,stats:e};this.upload(mI.WRTC_STATS,t)}upload(e,t){const i={_type:e,_message:t};try{this.websocket.sendMessage(i)}catch(e){const t=RC(\"MAX_UPLOAD_CACHE\")||50;this.uploadCache.push(i),this.uploadCache.length>t&&this.uploadCache.splice(0,1),this.uploadCache.length>0&&!this.uploadCacheInterval&&(this.uploadCacheInterval=window.setInterval((()=>{if(this.connectionState!==pI.CONNECTED)return;const e=this.uploadCache.splice(0,1)[0];0===this.uploadCache.length&&(window.clearInterval(this.uploadCacheInterval),this.uploadCacheInterval=void 0),this.upload(e._type,e._message)}),RC(\"UPLOAD_CACHE_INTERVAL\")||2e3))}}send(e,t){const i={_type:e,_message:t};this.websocket.sendMessage(i)}init(e,t){return this.initError=void 0,this.multiIpOption=void 0,this.joinResponse=void 0,this.reconnectToken=void 0,this.openConnectionTime=void 0,new cg(((i,n)=>{this.once(_I.WS_CONNECTED,(()=>i(this.joinResponse))),this.once(_I.WS_CLOSED,(()=>n(this.initError||new LI(Hg.WS_ABORT)))),this.connectionState=pI.CONNECTING,this.websocket.init(e).catch(n),this.websocket.once(gv.FAILBACK,(()=>{void 0===this.openConnectionTime&&n(new LI(Hg.INIT_DATACHANNEL_TIMEOUT))})),this.inflateDataTimer&&window.clearInterval(this.inflateDataTimer),this.inflateDataTimer=window.setInterval((()=>{this.handleInflateData()}),2e4),setTimeout((()=>{t&&void 0===this.openConnectionTime&&(jC.debug(\"[\".concat(this.clientId,\"] init datachannel timeout while join with failback to websocket\")),n(new LI(Hg.INIT_DATACHANNEL_TIMEOUT)))}),RC(\"DC_JOIN_WITH_FAILBACK\"))}))}close(e){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.inflateDataTimer&&(this.handleInflateData(),window.clearInterval(this.inflateDataTimer),this.inflateDataTimer=void 0),this.reconnectToken=void 0,this.joinResponse=void 0,this._disconnectedReason=e||ET.LEAVE,this.connectionState=pI.CLOSED,jC.debug(\"[\".concat(this.clientId,\"] \")+\"will close datachannel in signal\"),this.websocket.close(),e===ET.FALLBACK&&(this.websocket.removeAllListeners(),this.websocket=new Ny(\"gateway-\".concat(this.clientId),this.spec.retryConfig,!0,this.store),this.handleWebsocketEvents())}async join(){if(!this.joinResponse){this.emit(_I.ABORT_P2P_EXECUTION);const e=await vT(this,_I.DATACHANNEL_CONNECTING),t=await this.request(EI.JOIN,e);if(!t)return this.emit(_I.REPORT_JOIN_GATEWAY,Hg.TIMEOUT,this.url||\"\"),!1;this.joinResponse=t,this.emit(_I.JOIN_RESPONSE,this.joinResponse),this.reconnectToken=this.joinResponse.rejoin_token}return this.connectionState=pI.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),!0}async rejoin(){if(!this.reconnectToken)throw new LI(Hg.UNEXPECTED_ERROR,\"can not rejoin, no rejoin token\");const e=bT(this,_I.REQUEST_REJOIN_INFO);e.token=this.reconnectToken;const t=await this.request(EI.REJOIN,e);return!!t&&(this.connectionState=pI.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),t.peers&&t.peers.forEach((e=>{this.emit(fI.ON_USER_ONLINE,{uid:e.uid}),e.audio&&this.emit(fI.ON_ADD_AUDIO_STREAM,{uid:e.uid,uint_id:e.uint_id,audio:!0,ssrcId:e.audio_ssrc}),e.video&&this.emit(fI.ON_ADD_VIDEO_STREAM,{uid:e.uid,uint_id:e.uint_id,video:!0,ssrcId:e.video_ssrc}),e.audio_mute?this.emit(fI.MUTE_AUDIO,{uid:e.uid}):this.emit(fI.UNMUTE_AUDIO,{uid:e.uid}),e.video_mute?this.emit(fI.MUTE_VIDEO,{uid:e.uid}):this.emit(fI.UNMUTE_VIDEO,{uid:e.uid}),e.audio_enable_local?this.emit(fI.ENABLE_LOCAL_AUDIO,{uid:e.uid}):this.emit(fI.DISABLE_LOCAL_AUDIO,{uid:e.uid}),e.video_enable_local?this.emit(fI.ENABLE_LOCAL_VIDEO,{uid:e.uid}):this.emit(fI.DISABLE_LOCAL_VIDEO,{uid:e.uid}),e.audio||e.video||this.emit(fI.ON_REMOVE_STREAM,{uid:e.uid,uint_id:e.uint_id})})),!0)}reconnect(e,t){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.websocket.reconnect(e,t)}handleNotification(e){jC.debug(\"[\".concat(this.clientId,\"] receive notification: \"),e);const t=kv(e.code);if(\"success\"!==t.action){if(\"failed\"!==t.action)return\"quit\"===t.action?(\"ERR_REPEAT_JOIN_CHANNEL\"===t.desc&&this.close(ET.UID_BANNED),void this.close()):void this.reconnect(t.action,fv.SERVER_ERROR);jC.error(\"[\".concat(this.clientId,\"] ignore error: \"),t.desc)}}handlePingPong(){if(!this.websocket||\"connected\"!==this.websocket.state)return;this.pingpongTimeoutCount>0&&this.rttRolling.add(3e3),this.pingpongTimeoutCount+=1;const e=RC(\"PING_PONG_TIME_OUT\"),t=Date.now();this.pingpongTimeoutCount>=e&&(jC.warning(\"PINGPONG Timeout. Last Socket Message: \".concat(t-this.lastMsgTime,\"ms\")),t-this.lastMsgTime>RC(\"WEBSOCKET_TIMEOUT_MIN\"))?this.reconnect(\"retry\",fv.TIMEOUT):this.request(EI.PING,void 0,!0).then((()=>{this.pingpongTimeoutCount=0;const e=Date.now()-t;this.rttRolling.add(e),RC(\"REPORT_STATS\")&&this.send(EI.PING_BACK,{pingpongElapse:e})})).catch((e=>{}))}handleInflateData(){const{inflateLength:e,deflateLength:t}=this.websocket.getInflateData();0!==e&&0!==t&&this.upload(mI.WS_INFLATE_DATA_LENGTH,{ws_deflate_length:t,ws_inflate_length:e})}handleWebsocketEvents(){this.websocket.on(gv.RECONNECT_WAITTING_FINISH,(e=>{this.emit(_I.WS_RECONNECT_WAITTING_FINISH,e)})),this.websocket.on(gv.RECONNECT_CREATE_CONNECTION,(e=>{this.emit(_I.WS_RECONNECT_CREATE_CONNECTION,e)})),this.websocket.on(gv.ON_MESSAGE,this.onWebsocketMessage),this.websocket.on(gv.CLOSED,(()=>{this.connectionState=pI.CLOSED})),this.websocket.on(gv.FAILED,(()=>{this._disconnectedReason=ET.NETWORK_ERROR,this.connectionState=pI.CLOSED})),this.websocket.on(gv.RECONNECTING,(e=>{this._websocketReconnectReason=e,this.joinResponse=void 0,this.connectionState===pI.CONNECTED?this.connectionState=pI.RECONNECTING:this.connectionState=pI.CONNECTING})),this.websocket.on(gv.WILL_RECONNECT,((e,t)=>{if(bT(this,_I.IS_P2P_DISCONNECTED)&&\"retry\"===e)return jC.debug(\"\".concat(this.clientId,\" reconnect mode is retry, but p2p lost, change to tryNext\")),this.reconnectToken=void 0,this.emit(_I.NEED_RENEW_SESSION),this.emit(_I.DISCONNECT_P2P),t(\"tryNext\");\"retry\"!==e&&(jC.debug(\"\".concat(this.clientId,\" websockt will_connect event, renewSession reconnectMode is \").concat(e)),this.reconnectToken=void 0,this.emit(_I.NEED_RENEW_SESSION),this.emit(_I.DISCONNECT_P2P)),t(e)})),this.websocket.on(gv.CONNECTED,(()=>{this.openConnectionTime=Date.now(),this.reconnectToken?this.rejoin().catch((e=>{jC.warning(\"[\".concat(this.clientId,\"] rejoin failed \").concat(e)),this.reconnect(\"tryNext\",fv.SERVER_ERROR)})):this.join().catch((e=>{if(this.emit(_I.REPORT_JOIN_GATEWAY,e.message||e.code,this.url||\"\"),e instanceof LI&&e.code===Hg.UNEXPECTED_RESPONSE&&e.data.code===hI.ERR_NO_AUTHORIZED)return jC.warning(\"[\".concat(this.clientId,\"] reconnect no authorized, recover\")),void this.reconnect(\"recover\",fv.SERVER_ERROR);jC.error(\"[\".concat(this.clientId,\"] join gateway request failed\"),e.toString()),this.spec.forceWaitGatewayResponse?this.reconnect(\"tryNext\",fv.SERVER_ERROR):(this.initError=e,this.close())}))})),this.websocket.on(gv.REQUEST_NEW_URLS,((e,t)=>{vT(this,_I.REQUEST_RECOVER,this.multiIpOption).then(e).catch(t)})),this.websocket.on(gv.ON_TOKEN_PRIVILEGE_DID_EXPIRE,(()=>{this.emit(fI.ON_TOKEN_PRIVILEGE_DID_EXPIRE)})),this.websocket.on(gv.TO_CONNECT_DATACHANNEL,(async(e,t,i)=>vT(this,_I.DATACHANNEL_PRECONNECT,e).then(t).catch(i))),this.websocket.on(gv.FAILBACK,(()=>{void 0!==this.openConnectionTime&&this.emit(_I.DATACHANNEL_FAILBACK)}))}}class Py extends dT{constructor(e,t){super(),sh(this,\"signal\",void 0),sh(this,\"token\",void 0),sh(this,\"tokenTimeout\",void 0),sh(this,\"tokenInterval\",void 0),sh(this,\"_sequence\",0),sh(this,\"userMap\",new Map),sh(this,\"encoder\",new TextEncoder),this.signal=e,this.token=t;const i=()=>{this.signal.connectionState===pI.CONNECTED&&this.check(),0===this.userMap.size?this.tokenInterval=window.setTimeout(i,1e3):this.tokenInterval=window.setTimeout(i,3*RC(\"P2P_TOKEN_INTERVAL\"))};i()}async send(e,t,i,n,r){var s,o,a;if(0===this.userMap.size)return;const c=Array.from(NI(s=this.userMap).call(s))[0].token;\"string\"!=typeof t&&(t=JSON.stringify(t)),n=null!==(o=n)&&void 0!==o?o:nS(6,\"\"),r=null!==(a=r)&&void 0!==a?a:this._sequence++;const d={_id:n,_type:e,_seq:r,_message:t,token:\"\".concat(this.token,\"_\").concat(c)};RC(\"SHOW_P2P_LOG\")&&jC.debug(\"send message\",d,\"noNeedResponse : \".concat(i));this.splitMessage(JSON.stringify(d)).forEach((e=>{this.signal.request(EI.DATA_STREAM,{payload:QT(this.encoder.encode(e))})}));const l=new cg(((t,r)=>{const s=window.setTimeout((()=>{this.off(\"res-@\".concat(n,\"_ack\"),o),this.off(\"res-@\".concat(n),c),this.off(yv.ABORT,a),jC.debug(\"[external-signal] request timeout, type: \".concat(e,\", requestId: \").concat(n)),0===this.userMap.size?r(new Kg(Hg.INVALID_REMOTE_USER)):r(new Kg(Hg.TIMEOUT))}),RC(\"EXTERNAL_SIGNAL_REQUEST_TIMEOUT\")),o=()=>{s&&window.clearTimeout(s),this.off(yv.ABORT,a),i&&t()},a=()=>{s&&window.clearTimeout(s),this.off(\"res-@\".concat(n,\"_ack\"),o),this.off(\"res-@\".concat(n),c),r(new Kg(Hg.EXTERNAL_SIGNAL_ABORT,\"type: \".concat(e,\", requestId: \").concat(n)))};this.once(yv.ABORT,a),this.once(\"res-@\".concat(n,\"_ack\"),o);const c=(i,c)=>{l=!0,s&&window.clearTimeout(s),this.off(\"res-@\".concat(n,\"_ack\"),o),this.off(yv.ABORT,a),\"success\"===i?t(c):r(new Kg(Hg.P2P_MESSAGE_FAILED,\"request \".concat(e,\" failed, requestId: \").concat(n)))};let l=!1;i||(this.once(\"res-@\".concat(n),c),iS(RC(\"SIGNAL_REQUEST_TIMEOUT\")).then((()=>{l||jC.warning(\"external_signal request timeout, type: \".concat(e,\", requestId: \").concat(n,\", \").concat(d))})))}));try{return await l}catch(s){if(s.code===Hg.TIMEOUT)return await this.send(e,t,i,n,r);throw s}}onMessage(e){var t;const{_uid:i}=e;let n,r=this.userMap.get(i);if(r)n=r.splitMessageMap;else{if(this.userMap.size>0||!(\"_type\"in e)||e._type!==vv.CHECK)return;const{token:t}=e;n=new Map,r={uid:i,isStart:!0,token:t,splitMessageMap:n,nextExpectedSequenceNumber:0,receivedMessagesMap:new Map},this.userMap.set(i,r),this.signal.emit(fI.ON_USER_ONLINE,{uid:i}),this.handleUserOnline()}if(\"id\"in e&&\"total\"in e){var s;const{id:t,total:r}=e,o=null!==(s=n.get(t))&&void 0!==s?s:[];if(o.push(e),n.has(t)||n.set(t,o),o.length!==r)return;{const r=ep(o).call(o,((e,t)=>e.index-t.index)).map((e=>e.payload)).join(\"\");n.delete(t),(e=JSON.parse(r))._uid=i}}const{_type:o,token:a}=e;if(bn(t=[vv.ACK,vv.CHECK]).call(t,o))return o===vv.CHECK&&this.handleCheckToken(r,a),void this.receiveMessage(e);a===\"\".concat(r.token,\"_\").concat(this.token)?this.handleReceivedMessage(e):jC.debug('Receive unexpected message\", '.concat(a,\", cur_token: \").concat(r.token,\"_\").concat(this.token),e)}check(){const e={_id:nS(6,\"\"),token:this.token,_type:vv.CHECK};RC(\"SHOW_P2P_LOG\")&&jC.debug(\"send message\",e),this.signal.request(EI.DATA_STREAM,{payload:QT(this.encoder.encode(JSON.stringify(e)))})}ack(e){const t={_id:e,_type:vv.ACK,token:this.token};RC(\"SHOW_P2P_LOG\")&&jC.debug(\"send message\",t),this.signal.request(EI.DATA_STREAM,{payload:QT(this.encoder.encode(JSON.stringify(t)))})}response(e,t,i){this.send(vv.RESPONSE,JSON.stringify({success:!i,message:t}),!0,e)}handleReceivedMessage(e){const t=()=>{this.userMap.forEach((e=>{const{receivedMessagesMap:t,nextExpectedSequenceNumber:i}=e;for(;t.has(i);){const n=t.get(i);t.delete(i),this.receiveMessage(n),e.nextExpectedSequenceNumber++}}))};if(!e)return void t();const{_uid:i,_seq:n}=e,r=this.userMap.get(i),{receivedMessagesMap:s,isStart:o,nextExpectedSequenceNumber:a}=r;if(n{this.response(e._id,t)})).catch((()=>{this.response(e._id,void 0,!0)}));break;case vv.ACK:this.getListeners(\"res-@\".concat(t,\"_ack\")).length>0&&this.emit(\"res-@\".concat(t,\"_ack\"));break;case vv.RESPONSE:{const{success:e,message:i}=s;this.emit(\"res-@\".concat(t),e?\"success\":\"failed\",i);break}}}}splitMessage(e){if(e.length0;){r++;const a={id:n,index:r,total:o,payload:e.slice(0,s),token:\"\".concat(this.token,\"_\").concat(i)};JSON.stringify(a).length>Py.MAX_MESSAGE_SIZE?s-=50:(t.push(a),e=e.slice(s))}return t.map((e=>JSON.stringify(e)))}handleCheckToken(e,t){return e.token!==t?(jC.debug(\"token changed, from \".concat(e.token,\" to \").concat(t)),this.reset(e.uid,t),!1):(this.tokenTimeout&&(window.clearTimeout(this.tokenTimeout),this.tokenTimeout=void 0),this.tokenTimeout=window.setTimeout((()=>{jC.debug(\"token timeout, \".concat(t)),this.reset(e.uid)}),RC(\"MAX_P2P_TIMEOUT\")),!0)}async handleUserOnline(){const e=await vT(this.signal,vv.CALL,void 0),t=await this.send(vv.CALL,e);this.signal.emit(_I.P2P_CONNECTION,t,!0)}async reset(e,t){const i=this.userMap.get(e);i&&(this.emit(yv.ABORT),this.signal.emit(fI.ON_USER_OFFLINE,{uid:i.uid,reason:wv.P2P_TOKEN_CHANGED}),this._sequence=0,this.userMap.clear(),t||(jC.debug(\"change local token from \".concat(t,\" to \").concat(t)),this.token=nS(6,\"\")))}clear(){this._sequence=0,this.userMap.clear(),this.tokenInterval&&window.clearTimeout(this.tokenInterval),this.tokenInterval=void 0,this.tokenTimeout&&window.clearTimeout(this.tokenTimeout),this.tokenTimeout=void 0,this.emit(yv.ABORT)}}sh(Py,\"MAX_SIZE\",1),sh(Py,\"MAX_MESSAGE_SIZE\",1024);class Ly extends dT{get connectionState(){return this._connectionState}set connectionState(e){e!==this._connectionState&&(this._connectionState=e,e===pI.CONNECTED?this.emit(_I.WS_CONNECTED):e===pI.RECONNECTING?this.emit(_I.WS_RECONNECTING,this._websocketReconnectReason):e===pI.CLOSED&&this.emit(_I.WS_CLOSED,this._disconnectedReason))}get currentURLIndex(){return this.websocket.currentURLIndex}get url(){return this.websocket&&this.websocket.url||null}get rtt(){return this.rttRolling.mean()}constructor(e,t){super(),sh(this,\"_disconnectedReason\",void 0),sh(this,\"_websocketReconnectReason\",void 0),sh(this,\"_connectionState\",pI.CLOSED),sh(this,\"reconnectToken\",void 0),sh(this,\"p2pToken\",void 0),sh(this,\"websocket\",void 0),sh(this,\"openConnectionTime\",void 0),sh(this,\"clientId\",void 0),sh(this,\"lastMsgTime\",Date.now()),sh(this,\"uploadCache\",[]),sh(this,\"uploadCacheInterval\",void 0),sh(this,\"rttRolling\",new gS(5)),sh(this,\"pingpongTimer\",void 0),sh(this,\"pingpongTimeoutCount\",0),sh(this,\"joinResponse\",void 0),sh(this,\"multiIpOption\",void 0),sh(this,\"initError\",void 0),sh(this,\"spec\",void 0),sh(this,\"store\",void 0),sh(this,\"_external_signal\",void 0),sh(this,\"onWebsocketMessage\",(e=>{if(e.data instanceof ArrayBuffer)return void this.emit(_I.ON_BINARY_DATA,e.data);const t=JSON.parse(e.data);if(this.lastMsgTime=Date.now(),Object.prototype.hasOwnProperty.call(t,\"_id\")){const e=\"res-@\".concat(t._id);this.emit(e,t._result,t._message)}else if(Object.prototype.hasOwnProperty.call(t,\"_type\")){switch(t._type){case fI.ON_DATA_STREAM:return void this.handleDataStream(t._message);case fI.MUTE_AUDIO:case fI.MUTE_VIDEO:case fI.ON_P2P_LOST:case fI.ON_USER_ONLINE:return;case fI.ON_USER_OFFLINE:const{uid:e}=t._message;return jC.debug(\"[\".concat(this.clientId,\"] user-offline uid: \").concat(e)),void this._external_signal.reset(e)}if(this.emit(t._type,t._message),t._type===fI.ON_NOTIFICATION&&this.handleNotification(t._message),t._type===fI.ON_USER_BANNED)switch(t._message.error_code){case 14:this.close(ET.UID_BANNED);break;case 15:this.close(ET.IP_BANNED);break;case 16:this.close(ET.CHANNEL_BANNED)}if(t._type===fI.ON_USER_LICENSE_BANNED)switch(t._message.error_code){case hI.ERR_LICENSE_MISSING:this.close(ET.LICENSE_MISSING);break;case hI.ERR_LICENSE_EXPIRED:this.close(ET.LICENSE_EXPIRED);break;case hI.ERR_LICENSE_MINUTES_EXCEEDED:this.close(ET.LICENSE_MINUTES_EXCEEDED);break;case hI.ERR_LICENSE_PERIOD_INVALID:this.close(ET.LICENSE_PERIOD_INVALID);break;case hI.ERR_LICENSE_MULTIPLE_SDK_SERVICE:this.close(ET.LICENSE_MULTIPLE_SDK_SERVICE);break;case hI.ERR_LICENSE_ILLEGAL:this.close(ET.LICENSE_ILLEGAL);break;default:this.close()}}})),this.clientId=e.clientId,this.spec=e,this.store=t,this.websocket=new qv(\"gateway-\".concat(this.clientId),this.spec.retryConfig,!0,RC(\"JOIN_GATEWAY_USE_DUAL_DOMAIN\"),RC(\"JOIN_GATEWAY_USE_443PORT_ONLY\"),t),this.handleWebsocketEvents(),window.addEventListener(\"offline\",(()=>{this.connectionState===pI.CONNECTED&&this.reconnect(\"retry\",fT.OFFLINE)})),this.p2pToken=nS(6,\"\"),this._external_signal=new Py(this,this.p2pToken)}async request(e,t,i,n){const r=nS(6,\"\"),s={_id:r,_type:e,_message:t},o=this.websocket.connectionID,a=()=>new cg(((e,t)=>{if(this.connectionState===pI.CONNECTED)return e();const i=()=>{this.off(_I.WS_CLOSED,n),e()},n=()=>{this.off(_I.WS_CONNECTED,i),t(new Kg(Hg.WS_ABORT))};this.once(_I.WS_CONNECTED,i),this.once(_I.WS_CLOSED,n)}));if(this.connectionState!==pI.CONNECTING&&this.connectionState!==pI.RECONNECTING||e===EI.JOIN||e===EI.REJOIN||await a(),this.websocket.sendMessage(s,!0),n)return;const c=new cg(((i,n)=>{let s=!1;const a=(n,r)=>{s=!0,i({isSuccess:\"success\"===n,message:r||{}}),this.off(_I.WS_CLOSED,c),this.off(_I.WS_RECONNECTING,c),this.emit(_I.REQUEST_SUCCESS,e,t)};this.once(\"res-@\".concat(r),a);const c=()=>{n(new Kg(Hg.WS_ABORT,\"type: \".concat(e))),this.off(_I.WS_CLOSED,c),this.off(_I.WS_RECONNECTING,c),this.off(\"res-@\".concat(r),a)};this.once(_I.WS_CLOSED,c),this.once(_I.WS_RECONNECTING,c),iS(RC(\"SIGNAL_REQUEST_TIMEOUT\")).then((()=>{this.websocket.connectionID!==o||s||(jC.warning(\"[\".concat(this.clientId,\"] ws request timeout, type: \").concat(e)),this.emit(_I.REQUEST_TIMEOUT,e,t))}))}));let d=null;try{d=await c}catch(n){if(this.connectionState===pI.CLOSED||e===EI.LEAVE)throw new Kg(Hg.WS_ABORT);return!this.spec.forceWaitGatewayResponse||i?n.throw():e===EI.JOIN||e===EI.REJOIN?null:(await a(),await this.request(e,t))}if(d.isSuccess)return d.message;const l=Number(d.message.error_code||d.message.code),u=kv(l),h=new Kg(Hg.UNEXPECTED_RESPONSE,\"\".concat(u.desc,\": \").concat(d.message.error_str),{code:l,data:d.message});return\"success\"===u.action?d.message:(jC.warning(\"[\".concat(this.clientId,\"] [\").concat(this.websocket.connectionID,\"] unexpected response from type \").concat(e,\", error_code: \").concat(l,\", message: \").concat(u.desc,\", action: \").concat(u.action)),l===hI.ERR_TOO_MANY_BROADCASTERS?e===EI.JOIN||e===EI.REJOIN?(this.initError=h,this.close(),h.throw()):h.throw():\"failed\"===u.action?h.throw():\"quit\"===u.action?(this.initError=h,this.close(),h.throw()):(l===hI.ERR_JOIN_BY_MULTI_IP?(this.multiIpOption=d.message.option,jC.warning(\"[\".concat(this.clientId,\"] detect multi ip, recover\")),this.reconnect(\"recover\",fT.MULTI_IP)):this.reconnect(u.action,fT.SERVER_ERROR),e===EI.JOIN||e===EI.REJOIN?null:await this.request(e,t)))}waitMessage(e,t){return new cg((i=>{const n=r=>{(!t||t(r))&&(this.off(e,n),i(r))};this.on(e,n)}))}uploadWRTCStats(e){if(!this.store.sessionId)return void jC.warn(\"[\".concat(this.clientId,\"] no session id when upload wrtc stats\"));const t={lts:Date.now(),sid:this.store.sessionId,uid:this.store.intUid,stats:e};this.upload(mI.WRTC_STATS,t)}upload(e,t){const i={_type:e,_message:t};try{this.websocket.sendMessage(i)}catch(e){const t=RC(\"MAX_UPLOAD_CACHE\")||50;this.uploadCache.push(i),this.uploadCache.length>t&&this.uploadCache.splice(0,1),this.uploadCache.length>0&&!this.uploadCacheInterval&&(this.uploadCacheInterval=window.setInterval((()=>{if(this.connectionState!==pI.CONNECTED)return;const e=this.uploadCache.splice(0,1)[0];0===this.uploadCache.length&&(window.clearInterval(this.uploadCacheInterval),this.uploadCacheInterval=void 0),this.upload(e._type,e._message)}),RC(\"UPLOAD_CACHE_INTERVAL\")||2e3))}}send(e,t){const i={_type:e,_message:t};this.websocket.sendMessage(i)}async sendExtensionMessage(e,t,i){return await this._external_signal.send(e,t,i)}init(e){return this.initError=void 0,this.multiIpOption=void 0,this.joinResponse=void 0,this.reconnectToken=void 0,this.openConnectionTime=void 0,new cg(((t,i)=>{this.once(_I.WS_CONNECTED,(()=>t(this.joinResponse))),this.once(_I.WS_CLOSED,(()=>i(this.initError||new Kg(Hg.WS_ABORT)))),this.connectionState=pI.CONNECTING,this.websocket.init(e).catch(i)}))}close(e){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.reconnectToken=void 0,this.joinResponse=void 0,this._external_signal.clear(),this._disconnectedReason=e||ET.LEAVE,this.connectionState=pI.CLOSED,jC.debug(\"[\".concat(this.clientId,\"] \")+\"will close websocket in signal\"),this.websocket.close(),e===ET.FALLBACK&&(this.websocket.removeAllListeners(),this.websocket=new qv(\"gateway-\".concat(this.clientId),this.spec.retryConfig,!0,RC(\"JOIN_GATEWAY_USE_DUAL_DOMAIN\"),RC(\"JOIN_GATEWAY_USE_443PORT_ONLY\"),this.store),this.handleWebsocketEvents()),this.p2pToken=nS(6,\"\"),this._external_signal.clear(),this._external_signal=new Py(this,this.p2pToken)}async join(){if(!this.joinResponse){this.emit(_I.ABORT_P2P_EXECUTION);const e=await vT(this,_I.REQUEST_JOIN_INFO),t=await this.request(EI.JOIN,e);if(!t)return this.emit(_I.REPORT_JOIN_GATEWAY,Hg.TIMEOUT,this.url||\"\"),!1;this.joinResponse=t,this.emit(_I.JOIN_RESPONSE,this.joinResponse),this.reconnectToken=this.joinResponse.rejoin_token}return this.connectionState=pI.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),!0}reconnect(e,t){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.websocket.reconnect(e,t)}handleDataStream(e){try{var t;const i=XT(e.payload),n=(new TextDecoder).decode(i),r=JSON.parse(n);\"total\"in r&&\"id\"in r||bn(t=Object.values(vv)).call(t,r._type)?(r._uid=e.uid,this._external_signal.onMessage(r)):this.emit(fI.ON_DATA_STREAM,e)}catch(t){this.emit(fI.ON_DATA_STREAM,e)}}handleNotification(e){jC.debug(\"[\".concat(this.clientId,\"] receive notification: \"),e);const t=kv(e.code);if(\"success\"!==t.action){if(\"failed\"!==t.action)return\"quit\"===t.action?(\"ERR_REPEAT_JOIN_CHANNEL\"===t.desc&&this.close(ET.UID_BANNED),void this.close()):void this.reconnect(t.action,fT.SERVER_ERROR);jC.error(\"[\".concat(this.clientId,\"] ignore error: \"),t.desc)}}handlePingPong(){if(!this.websocket||\"connected\"!==this.websocket.state)return;this.pingpongTimeoutCount>0&&this.rttRolling.add(3e3),this.pingpongTimeoutCount+=1;const e=RC(\"PING_PONG_TIME_OUT\"),t=Date.now();this.pingpongTimeoutCount>=e&&(jC.warning(\"[\".concat(this.clientId,\"] PINGPONG Timeout. Last Socket Message: \").concat(t-this.lastMsgTime,\"ms\")),t-this.lastMsgTime>RC(\"WEBSOCKET_TIMEOUT_MIN\"))?this.reconnect(\"retry\",fT.TIMEOUT):this.request(EI.PING,void 0,!0).then((()=>{this.pingpongTimeoutCount=0;const e=Date.now()-t;this.rttRolling.add(e),RC(\"REPORT_STATS\")&&this.send(EI.PING_BACK,{pingpongElapse:e})})).catch((e=>{}))}handleWebsocketEvents(){this.websocket.on(SI.RECONNECT_WAITTING_FINISH,(e=>{this.emit(_I.WS_RECONNECT_WAITTING_FINISH,e)})),this.websocket.on(SI.RECONNECT_CREATE_CONNECTION,(e=>{this.emit(_I.WS_RECONNECT_CREATE_CONNECTION,e)})),this.websocket.on(SI.ON_MESSAGE,this.onWebsocketMessage),this.websocket.on(SI.CLOSED,(()=>{this.connectionState=pI.CLOSED})),this.websocket.on(SI.FAILED,(()=>{this._disconnectedReason=ET.NETWORK_ERROR,this.connectionState=pI.CLOSED})),this.websocket.on(SI.RECONNECTING,(e=>{this._websocketReconnectReason=e,this.joinResponse=void 0,this.connectionState===pI.CONNECTED?this.connectionState=pI.RECONNECTING:this.connectionState=pI.CONNECTING})),this.websocket.on(SI.WILL_RECONNECT,((e,t,i)=>{\"retry\"!==e?(jC.debug(\"\".concat(this.clientId,\" websocket will_connect event, renewSession reconnectMode is \").concat(e)),this.reconnectToken=void 0,this.emit(_I.NEED_RENEW_SESSION)):jC.debug(\"\".concat(this.clientId,\" reconnect mode is retry, no need to renew session\")),i(e)})),this.websocket.on(SI.CONNECTED,(()=>{this.openConnectionTime=Date.now(),this.join().catch((e=>{if(this.emit(_I.REPORT_JOIN_GATEWAY,e.message||e.code,this.url||\"\"),e instanceof Kg&&e.code===Hg.UNEXPECTED_RESPONSE&&e.data.code===hI.ERR_NO_AUTHORIZED)return jC.warning(\"[\".concat(this.clientId,\"] reconnect no authorized, recover\")),void this.reconnect(\"recover\",fT.SERVER_ERROR);jC.error(\"[\".concat(this.clientId,\"] join gateway request failed\"),e.toString()),this.spec.forceWaitGatewayResponse?this.reconnect(\"tryNext\",fT.SERVER_ERROR):(this.initError=e,this.close())}))})),this.websocket.on(SI.REQUEST_NEW_URLS,((e,t)=>{vT(this,_I.REQUEST_RECOVER,this.multiIpOption).then(e).catch(t)})),this.websocket.on(SI.ON_TOKEN_PRIVILEGE_DID_EXPIRE,(()=>{this.emit(fI.ON_TOKEN_PRIVILEGE_DID_EXPIRE)}))}}function ky(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function My(e){for(var t=1;t255||\"\".concat(e.apResponse.cid,\"_\").concat(e.apResponse.cert).length<22?(jC.debug(\"[\".concat(this.store.clientId,\"] Dc is not supported, because ticket length is incorrect, it has to be between 22 and 255\")),t=!0):e.apResponse.addresses.some((e=>e.fingerprint))||RC(\"FINGERPRINT\")||(jC.debug(\"[\".concat(this.store.clientId,\"] Dc is not supported, because fingerprint does not exist\")),t=!0),t&&this.resetSignal()}this.store.joinGatewayStart(),\"disabled\"!==e.cloudProxyServer&&(this.hasChangeBGPAddress=!0);const n=Date.now();let r=Uy.get(e.cname);if(r||(r=new Map,Uy.set(e.cname,r)),this._isProactiveJoin=!0,r.has(e.uid)){const t=new LI(Hg.UID_CONFLICT);throw eI.joinGateway(e.sid,{lts:n,succ:!1,ec:t.message,addr:null,uid:e.uid,cid:e.cid,firstSuccess:this._isProactiveJoin,avoidJoinStartTime:this.store.avoidJoinStart,isProxy:!!e.proxyServer,signalChannel:this.signal instanceof Dy?\"1\":\"0\"}),this._isProactiveJoin=!1,t}r.set(e.uid,!0),this.joinInfo=e,this.key=t;let s=0;this.joinGatewayStartTime=n;const o=e.proxyServer;try{let t;if(jC.debug(\"[\".concat(this.store.clientId,\"] use \").concat(this.signal instanceof Dy?\"datachannel\":\"websocket\",\" join uid \").concat(s)),this.signal instanceof Dy)t=await this.signal.init(e.apResponse.addresses,i);else{const n=e.gatewayAddrs.map((t=>{let{address:i}=t;const[n,r]=i.split(\":\"),s={host:n,port:r};return e.proxyServer&&(s.proxy=e.proxyServer),s}));t=await this.signal.init(n,i)}s=t.uid,jC.debug(\"[\".concat(this.store.clientId,\"] \").concat(this.signal instanceof Dy?\"datachannel\":\"websocket\",\" join uid \").concat(s,\" cost \").concat(Date.now()-this.joinGatewayStartTime))}catch(t){if(t&&t.code===Hg.INIT_WEBSOCKET_TIMEOUT)throw jC.warning(\"[\".concat(this.store.clientId,\"] User join failed\"),t.toString()),t;if(t&&t.code===Hg.INIT_DATACHANNEL_TIMEOUT)throw jC.warning(\"[\".concat(this.store.clientId,\"] User join datachannel failed\"),t.toString()),this.resetSignal(),t;throw jC.error(\"[\".concat(this.store.clientId,\"] User join failed\"),t.toString()),eI.joinGateway(e.sid,{lts:n,succ:!1,ec:t.message,addr:this.signal.url,uid:e.uid,cid:e.cid,firstSuccess:this._isProactiveJoin,avoidJoinStartTime:this.store.avoidJoinStart,isProxy:!!o,signalChannel:this.signal instanceof Dy?\"1\":\"0\"}),this._isProactiveJoin=!1,r.delete(e.uid),this.signal.close(),t}return this.state=\"CONNECTED\",this.inChannelInfo.joinAt=Date.now(),jC.debug(\"[\".concat(this.store.clientId,\"] Connected to gateway server\")),this.trafficStatsInterval=window.setInterval((()=>{this.updateTrafficStats().catch((e=>{jC.warning(\"[\".concat(this.store.clientId,\"] get traffic stats error\"),e.toString())}))}),3e3),this.networkQualityInterval=window.setInterval((()=>{navigator&&void 0!==navigator.onLine&&!navigator.onLine?this.emit(XI.NETWORK_QUALITY,{downlinkNetworkQuality:6,uplinkNetworkQuality:6}):this._signalTimeout?this.emit(XI.NETWORK_QUALITY,{downlinkNetworkQuality:5,uplinkNetworkQuality:5}):\"CONNECTED\"===this.state&&this._statsCollector.trafficStats?this.emit(XI.NETWORK_QUALITY,{uplinkNetworkQuality:Cy(this._statsCollector.trafficStats.B_unq),downlinkNetworkQuality:Cy(this._statsCollector.trafficStats.B_dnq)}):this.emit(XI.NETWORK_QUALITY,{uplinkNetworkQuality:0,downlinkNetworkQuality:0})}),2e3),this.store.joinGatewayEnd(),s}async leave(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=arguments.length>1?arguments[1]:void 0;if(\"DISCONNECTED\"!==this.state){t!==ET.FALLBACK&&(this.state=\"DISCONNECTING\");try{e||this.signal.connectionState!==pI.CONNECTED||await function(e,t){return t===1/0?e:cg.race([e,tS(t)])}(this.signal.request(EI.LEAVE,void 0,!0),3e3)}catch(e){jC.warning(\"[\".concat(this.store.clientId,\"] leave request failed, ignore\"),e)}this.signal.close(t),t!==ET.FALLBACK&&(this.state=\"DISCONNECTED\"),this.reset()}}async publish(e,t,i){if(\"CONNECTED\"!==this.state&&\"RECONNECTING\"!==this.state)throw new LI(Hg.INVALID_OPERATION,\"can not publish when connection state is \".concat(this.state));const n={state:\"offer\",p2p_id:this.store.p2pId,ortc:t,mode:this.spec.mode,extend:RC(\"PUB_EXTEND\"),twcc:!!RC(\"PUBLISH_TWCC\"),rtx:!!RC(\"USE_PUB_RTX\")};try{return(await this.signal.request(EI.PUBLISH,n,!0))._message}catch(n){if(i&&n.data&&n.data.code===hI.ERR_PUBLISH_REQUEST_INVALID)return jC.warning(\"[\".concat(this.store.clientId,\"] receive publish error code, retry\"),n.toString()),await this.tryUnpubBeforeRepub(e,t),this.publish(e,t,!1);throw n}}async publishDataChannel(e,t,i){var n;if(\"CONNECTED\"!==this.state&&\"RECONNECTING\"!==this.state)throw new LI(Hg.INVALID_OPERATION,\"can not publish when connection state is \".concat(this.state));const r={stream_id:t.streamId,ordered:t.ordered?1:0,max_retrans_times:null!==(n=t.maxRetransmits)&&void 0!==n?n:10,channel_id:t.channelId,metadata:t.metadata};try{await this.signal.request(EI.PUBLISH_DATASTREAM,r,!0)}catch(n){if(i&&n.data&&n.data.code===hI.ERR_PUBLISH_REQUEST_INVALID)return jC.warning(\"[\".concat(this.store.clientId,\"] receive publish datachannels error code, retry\"),n.toString()),await this.tryUnpubDataChannelBeforeRepub(e,t),this.publishDataChannel(e,t,!1);throw n}}async unpublish(e,t){try{if(\"CONNECTED\"!==this.state&&\"RECONNECTING\"!==this.state)throw new LI(Hg.INVALID_OPERATION,\"can not publish when connection state is \".concat(this.state));await this.signal.request(EI.UNPUBLISH,{stream_id:t,ortc:e},!0)}catch(e){jC.warning(\"[\".concat(this.store.clientId,\"] unpublish warning: \"),e)}}async unpublishDataChannel(e){try{if(\"CONNECTED\"!==this.state&&\"RECONNECTING\"!==this.state)throw new LI(Hg.INVALID_OPERATION,\"can not publish when connection state is \".concat(this.state));await cg.all(e.map((e=>this.signal.request(EI.UNPUBLISH_DATASTREAM,{channel_id:e},!0))))}catch(e){jC.warning(\"unpublish datachannels warning: \",e)}}async presubscribe(e,t,i){if(\"CONNECTED\"!==this.state&&\"RECONNECTING\"!==this.state)throw new LI(Hg.INVALID_OPERATION,\"can not presubscribe when connection state is \".concat(this.state));const n={stream_id:e,stream_type:t,mode:this.spec.mode,codec:this.spec.codec,p2p_id:this.store.p2pId,twcc:!!RC(\"SUBSCRIBE_TWCC\"),rtx:!!RC(\"USE_SUB_RTX\")||void 0,extend:RC(\"SUB_EXTEND\"),svc:Array.isArray(RC(\"SVC\"))&&0!==RC(\"SVC\").length?RC(\"SVC\"):void 0};try{return await this.signal.request(EI.PRE_SUBSCRIBE,n,!0)}catch(n){if(i&&n.data&&n.data.code===hI.ERR_SUBSCRIBE_REQUEST_INVALID)return jC.warning(\"[\".concat(this.store.clientId,\"] pre-subscribe error, retry\"),n.toString()),this.presubscribe(e,t,!1);throw n}}async subscribe(e,t,i){if(\"CONNECTED\"!==this.state&&\"RECONNECTING\"!==this.state)throw new LI(Hg.INVALID_OPERATION,\"can not subscribe when connection state is \".concat(this.state));const n={stream_id:e,stream_type:t.stream_type,mode:this.spec.mode,codec:this.spec.codec,p2p_id:this.store.p2pId,twcc:!!RC(\"SUBSCRIBE_TWCC\"),rtx:!!RC(\"USE_SUB_RTX\"),extend:RC(\"SUB_EXTEND\"),ssrcId:t.ssrcId,svc:Array.isArray(RC(\"SVC\"))&&0!==RC(\"SVC\").length?RC(\"SVC\"):void 0};try{return(await this.signal.request(EI.SUBSCRIBE,n,!0))._message}catch(n){if(i&&n.data&&n.data.code===hI.ERR_SUBSCRIBE_REQUEST_INVALID)return jC.warning(\"[\".concat(this.store.clientId,\"] receiver subscribe error code, retry\"),n.toString()),await this.tryUnsubBeforeResub(e,t),await this.subscribe(e,t,!1);throw n}}async subscribeDataChannel(e,t,i){if(\"CONNECTED\"!==this.state&&\"RECONNECTING\"!==this.state)throw new LI(Hg.INVALID_OPERATION,\"can not subscribe datachannel when connection state is \".concat(this.state));const n={uid:e,stream_id:t.id,channel_id:t.datachannelId};try{return void await this.signal.request(EI.SUBSCRIBE_DATASTREAM,n,!0)}catch(n){if(i&&n.data&&n.data.code===hI.ERR_SUBSCRIBE_REQUEST_INVALID)return jC.warning(\"[\".concat(this.store.clientId,\"] receiver subscribe datachannel error code, retry\"),n.toString()),await this.tryUnsubDataChannelBeforeResub(e,t),await this.subscribeDataChannel(e,t,!1);throw n}}async subscribeAll(e,t){if(\"CONNECTED\"!==this.state&&\"RECONNECTING\"!==this.state)throw new LI(Hg.INVALID_OPERATION,\"can not massSubscribe when connection state is \".concat(this.state));const i={p2p_id:this.store.p2pId,users:e,dtx:!1,rtx:!!RC(\"USE_SUB_RTX\")};try{return await this.signal.request(EI.SUBSCRIBE_STREAMS,i,!0)}catch(i){if(t&&i.data&&i.data.code===hI.ERR_SUBSCRIBE_REQUEST_INVALID)return jC.warning(\"[\".concat(this.store.clientId,\"] receiver massSubscribe error code, retry\"),i.toString()),await this.tryMassUnsubBeforeResub(e),await this.subscribeAll(e,!1);throw i}}async setVideoProfile(e){const t=function(e){if(!(e.bitrateMax&&e.bitrateMin&&e.frameRate&&e.height&&e.width))return;let t=e.frameRate,i=e.width,n=e.height,r=!0;return\"number\"!=typeof t&&(t=t.exact||t.ideal||t.max||t.min||0,t||(r=!1)),\"number\"!=typeof i&&(i=i.exact||i.ideal||i.max||i.min||0,i||(r=!1)),\"number\"!=typeof n&&(n=n.exact||n.ideal||n.max||n.min||0,t||(r=!1)),r?{stream_type:0,width:i,height:n,fps:t,start_bps:1e3*e.bitrateMax,min_bps:1e3*e.bitrateMin,target_bps:1e3*e.bitrateMax}:void 0}(e);if(t)return this.signal.request(EI.SET_VIDEO_PROFILE,t);jC.debug(\"[\".concat(this.store.clientId,\"] encoder config is not complete, do not report to gateway\"))}async unsubscribe(e,t){try{await this.signal.request(EI.UNSUBSCRIBE,{p2p_id:this.store.p2pId,ortc:e,stream_id:t},!0)}catch(e){jC.warning(\"[\".concat(this.store.clientId,\"] unsubscribe warning: \"),e)}}async unsubscribeDataChannel(e,t){try{if(\"CONNECTED\"!==this.state&&\"RECONNECTING\"!==this.state)throw new LI(Hg.INVALID_OPERATION,\"can not publish when connection state is \".concat(this.state));await cg.all(e.map((e=>this.signal.request(EI.UNSUBSCRIBE_DATASTREAM,{stream_id:e,uid:t},!0))))}catch(e){jC.warning(\"unsubscribeDataChannel warning: \",e)}}async massUnsubscribe(e){try{await this.signal.request(EI.UNSUBSCRIBE_STREAMS,e,!0)}catch(e){jC.warning(\"[\".concat(this.store.clientId,\"] massUnsubscribeAll warning: \"),e)}}async reconnectPC(e){const{iceParameters:t,dtlsParameters:i,rtpCapabilities:n}=e;return{gatewayEstablishParams:await this.signal.request(EI.CONNECT_PC,{p2p_id:this.store.p2pId,stream_id:this.store.uid,ortc:{iceParameters:t,dtlsParameters:i,rtpCapabilities:n}},!0),gatewayAddress:this.getCurrentGatewayAddress()}}getGatewayInfo(){return this.signal.request(EI.GATEWAY_INFO)}async renewToken(e){await this.signal.request(EI.RENEW_TOKEN,e),this.key=e.token}async setClientRole(e,t){if(t&&(this._clientRoleOptions=Object.assign({},t)),\"CONNECTED\"!==this.state)return void(this.role=e);let i,n=0;\"audience\"===e?this._clientRoleOptions&&this._clientRoleOptions.delay?(i=this._clientRoleOptions.delay,n=1):n=this._clientRoleOptions&&this._clientRoleOptions.level?this._clientRoleOptions.level:2:n=0,await this.signal.request(EI.SET_CLIENT_ROLE,{role:e,level:n,delay:i,client_ts:Date.now()}),this.role=e}async setRemoteVideoStreamType(e,t){await this.signal.request(EI.SWITCH_VIDEO_STREAM,{stream_id:e,stream_type:t})}async setDefaultRemoteVideoStreamType(e){await this.signal.request(EI.DEFAULT_VIDEO_STREAM,{stream_type:e})}async setStreamFallbackOption(e,t){await this.signal.request(EI.SET_FALLBACK_OPTION,{stream_id:e,fallback_type:t})}async pickSVCLayer(e,t){await this.signal.request(EI.PICK_SVC_LAYER,{stream_id:e,spatial_layer:t.spatialLayer,temporal_layer:t.temporalLayer})}async setRTM2Flag(e){await this.signal.request(EI.SET_RTM2_FLAG,{rtm2_flag:e})}async sendExtensionMessage(e,t,i){if(this.signal instanceof Ly)return this.signal.sendExtensionMessage(e,t,i)}getInChannelInfo(){return this.inChannelInfo.joinAt&&(this.inChannelInfo.duration=Date.now()-this.inChannelInfo.joinAt),My({},this.inChannelInfo)}async getGatewayVersion(){return(await this.signal.request(EI.GATEWAY_INFO)).version}reset(){if(this.inChannelInfo.joinAt&&(this.inChannelInfo.duration=Date.now()-this.inChannelInfo.joinAt,this.inChannelInfo.joinAt=null),this.trafficStatsInterval&&(window.clearInterval(this.trafficStatsInterval),this.trafficStatsInterval=void 0),this.joinInfo){const e=Uy.get(this.joinInfo.cname);e&&e.delete(this.joinInfo.uid)}this.joinInfo=void 0,this.key=void 0,this.networkQualityInterval&&(window.clearInterval(this.networkQualityInterval),this.networkQualityInterval=void 0)}updateTurnConfigFromSignal(){if(!this.joinInfo)return;const e=function(e){let t;return t=e.startsWith(\"dc\")?e.match(/(dc\\:\\/\\/)?([^:]+):(\\d+)/):e.match(/(wss\\:\\/\\/)?([^:]+):(\\d+)/),t?{username:iI.username,password:iI.password,turnServerURL:t[2],tcpport:parseInt(t[3])+30,udpport:parseInt(t[3])+30,forceturn:!1}:null}((\"disabled\"===this.joinInfo.cloudProxyServer?this.signal.url:this.joinInfo.gatewayAddrs[this.signal.currentURLIndex].address)||\"\");this.joinInfo.turnServer.serversFromGateway=[],e&&\"off\"!==this.joinInfo.turnServer.mode&&\"disabled\"===this.joinInfo.cloudProxyServer&&this.joinInfo.turnServer.serversFromGateway.push(My(My({},iI),{},{turnServerURL:e.turnServerURL,tcpport:e.tcpport,udpport:e.udpport,username:this.joinInfo.uid.toString(),password:this.joinInfo.token}))}async updateTrafficStats(){if(\"CONNECTED\"!==this.state)return;const e=await this.signal.request(EI.TRAFFIC_STATS,void 0,!0);e.timestamp=Date.now(),null!=e.ntp_offset&&(this.ntpOffset=e.ntp_offset),e.peer_delay.forEach((e=>{const t=this._statsCollector.trafficStats&&this._statsCollector.trafficStats.peer_delay.find((t=>t.peer_uid===e.peer_uid));t&&t.B_st!==e.B_st&&KT((()=>{this.emit(XI.STREAM_TYPE_CHANGE,e.peer_uid,e.B_st)}))})),this._statsCollector.updateTrafficStats(e)}getJoinMessage(e){if(!this.joinInfo||!this.key)throw new LI(Hg.UNEXPECTED_ERROR,\"can not generate join message, no join info\");const t=Object.assign({},this.joinInfo.apResponse);let i=RC(\"REPORT_APP_SCENARIO\");if(\"string\"!=typeof i)try{i=JSON.stringify(i)}catch(e){i=void 0}i&&i.length>128&&(i=void 0);const n=My({license:this.joinInfo.license,p2p_id:this.store.p2pId,session_id:this.joinInfo.sid,app_id:this.joinInfo.appId,channel_key:this.key,channel_name:this.joinInfo.cname,sdk_version:EC,browser:navigator.userAgent,process_id:RC(\"PROCESS_ID\"),mode:this.store.useP2P?\"p2p\":this.spec.mode,codec:this.spec.codec,role:this.role,has_changed_gateway:this.hasChangeBGPAddress,ap_response:t,extend:RC(\"JOIN_EXTEND\"),details:{6:this.joinInfo.stringUid,cservice_map:\"proxy3\"===this.joinInfo.cloudProxyServer?\"1\":\"proxy5\"===this.joinInfo.cloudProxyServer?\"2\":void 0},features:{rejoin:!0},optionalInfo:this.joinInfo.optionalInfo,appScenario:i,attributes:{userAttributes:{enablePublishedUserList:RC(\"ENABLE_PUBLISHED_USER_LIST\"),maxSubscription:RC(\"MAX_SUBSCRIPTION\"),subscribeAudioFilterTopN:\"number\"==typeof RC(\"SUBSCRIBE_AUDIO_FILTER_TOPN\")?RC(\"SUBSCRIBE_AUDIO_FILTER_TOPN\"):void 0,enablePublishAudioFilter:\"boolean\"==typeof RC(\"ENABLE_PUBLISH_AUDIO_FILTER\")?RC(\"ENABLE_PUBLISH_AUDIO_FILTER\"):void 0,enableUserLicenseCheck:\"boolean\"==typeof RC(\"ENABLE_USER_LICENSE_CHECK\")?RC(\"ENABLE_USER_LICENSE_CHECK\"):void 0,enableRTX:!0===RC(\"USE_PUB_RTX\")||!0===RC(\"USE_SUB_RTX\")||void 0,disableFEC:RC(\"DISABLE_FEC\"),enableNTPReport:!!RC(\"ENABLE_NTP_REPORT\")||void 0,enableInstantVideo:!!RC(\"ENABLE_INSTANT_VIDEO\")||void 0,enableDataStream2:\"boolean\"==typeof RC(\"ENABLE_DATASTREAM_2\")?RC(\"ENABLE_DATASTREAM_2\"):void 0,rtm2Flag:\"number\"==typeof this.joinInfo.rtmFlag?this.joinInfo.rtmFlag:void 0,enableUserAutoRebalanceCheck:!!RC(\"ENABLE_USER_AUTO_REBALANCE_CHECK\"),enableXR:\"boolean\"==typeof RC(\"USE_XR\")?RC(\"USE_XR\"):void 0}},join_ts:this.joinGatewayStartTime},e);return this.joinInfo.stringUid&&(n.string_uid=this.joinInfo.stringUid),this.joinInfo.aesmode&&this.joinInfo.aespassword&&(n.aes_mode=this.joinInfo.aesmode,RC(\"ENCRYPT_AES\")?(n.aes_secret=this.joinInfo.aespassword,n.aes_encrypt=!0):n.aes_secret=this.joinInfo.aespassword,this.joinInfo.aessalt&&(n.aes_salt=this.joinInfo.aessalt)),t.addresses[this.signal.websocket.currentURLIndex]&&(n.ap_response.ticket=t.addresses[this.signal.websocket.currentURLIndex].ticket,delete t.addresses),void 0!==this.joinInfo.defaultVideoStream&&(n.default_video_stream=this.joinInfo.defaultVideoStream),n}getRejoinMessage(){if(!this.joinInfo)throw new LI(Hg.UNEXPECTED_ERROR,\"can not generate rejoin message, no join info\");return{session_id:this.joinInfo.sid,channel_name:this.joinInfo.cname,cid:this.joinInfo.cid,uid:this.joinInfo.uid,vid:Number(this.joinInfo.vid)}}handleSignalEvents(){this.signal.on(_I.WS_RECONNECT_WAITTING_FINISH,(e=>{var t;bn(t=[\"tryNext\",\"recover\"]).call(t,e)&&this.joinInfo&&eI.adjustSessionStartTime(this.joinInfo.sid)})),this.signal.on(_I.WS_RECONNECT_CREATE_CONNECTION,(e=>{this.joinGatewayStartTime=Date.now()})),this.signal.on(_I.WS_RECONNECTING,(e=>{this.joinInfo&&eI.WebSocketQuit(this.joinInfo.sid,{lts:Date.now(),succ:-1,cname:this.joinInfo.cname,uid:this.joinInfo.uid,cid:this.joinInfo.cid,errorCode:e||fT.NETWORK_ERROR}),this.joinInfo&&(this.state=\"RECONNECTING\",eI.sessionInit(this.joinInfo.sid,{lts:(new Date).getTime(),extend:this.isSignalRecover?{recover:!0}:{rejoin:!0},cname:this.joinInfo.cname,appid:this.joinInfo.appId,mode:this.spec.mode,stringUid:this.joinInfo.stringUid,channelProfile:\"live\"===this.spec.mode?1:0,channelMode:0,lsid:this.joinInfo.sid,clientRole:\"audience\"===this.role?2:1}),this.isSignalRecover=!1,this.joinGatewayStartTime=Date.now())})),this.signal.on(_I.WS_CLOSED,(e=>{let t;switch(e){case ET.LEAVE:t=fT.LEAVE;break;case ET.UID_BANNED:case ET.IP_BANNED:case ET.CHANNEL_BANNED:case ET.SERVER_ERROR:t=fT.SERVER_ERROR;break;case ET.FALLBACK:t=fT.FALLBACK;break;case ET.LICENSE_MISSING:case ET.LICENSE_EXPIRED:case ET.LICENSE_MINUTES_EXCEEDED:case ET.LICENSE_PERIOD_INVALID:case ET.LICENSE_MULTIPLE_SDK_SERVICE:case ET.LICENSE_ILLEGAL:case ET.TOKEN_EXPIRE:t=e;break;default:t=fT.NETWORK_ERROR}jC.debug(\"[\".concat(this.store.clientId,\"] [signal] websocket closed, reason: \").concat(t||\"undefined -> \"+fT.NETWORK_ERROR)),this.joinInfo&&eI.WebSocketQuit(this.joinInfo.sid,{lts:Date.now(),succ:e===ET.LEAVE?1:-1,cname:this.joinInfo.cname,uid:this.joinInfo.uid,cid:this.joinInfo.cid,errorCode:t}),this._disconnectedReason=e,e!==ET.FALLBACK&&(this.state=\"DISCONNECTED\"),this.reset()})),this.signal.on(_I.WS_CONNECTED,(()=>{if(this.updateTurnConfigFromSignal(),this.state=\"CONNECTED\",this.joinInfo&&(\"audience\"===this.role&&this._clientRoleOptions&&(this._clientRoleOptions.level||this._clientRoleOptions.delay)&&(jC.debug(\"[\".concat(this.store.clientId,\"] patch to send set client role, role: \").concat(this.role,\", mode: \").concat(this.spec.mode,\", level: \").concat(this._clientRoleOptions.level,\", delay: \").concat(this._clientRoleOptions.delay)),this.setClientRole(this.role,this._clientRoleOptions)),eI.joinGateway(this.joinInfo.sid,{lts:this.joinGatewayStartTime,succ:!0,ec:null,vid:this.joinInfo.vid,addr:this.signal.url,uid:this.joinInfo.uid,cid:this.joinInfo.cid,firstSuccess:this._isProactiveJoin,avoidJoinStartTime:this.store.avoidJoinStart,isProxy:!!this.joinInfo.proxyServer,signalChannel:this.signal instanceof Dy?\"1\":\"0\"}),this._isProactiveJoin=!1,this.joinInfo.useLocalAccessPoint&&1===this.joinInfo.setLocalAPVersion)){const e=this.signal.url&&this.signal.url.match(/wss\\:\\/\\/([^:]+):(\\d+)/);if(!e)return void jC.error(\"[\".concat(this.store.clientId,\"] set local access point after joined failed: \").concat(e));SC(\"EVENT_REPORT_DOMAIN\",e[1]),SC(\"EVENT_REPORT_BACKUP_DOMAIN\",e[1]),SC(\"LOG_UPLOAD_SERVER\",\"\".concat(e[1],\":6444\"))}})),this.signal.on(fI.ON_UPLINK_STATS,(e=>{this._statsCollector.updateUplinkStats(e)})),this.signal.on(_I.REQUEST_RECOVER,((e,t,i)=>{if(!this.joinInfo)return i(new LI(Hg.UNEXPECTED_ERROR,\"gateway: can not recover, no join info\"));e&&(this.joinInfo.multiIP=e,this.hasChangeBGPAddress=!0),this.isSignalRecover=!0,vT(this,XI.REQUEST_NEW_GATEWAY_LIST).then(t).catch(i)})),this.signal.on(_I.REQUEST_JOIN_INFO,(async e=>{var t;if(this.updateTurnConfigFromSignal(),this.store.useP2P)return void e(this.getJoinMessage({ortc:{}}));const{iceParameters:i,dtlsParameters:n,rtpCapabilities:r}=await vT(this,XI.REQUEST_P2P_CONNECTION_PARAMS,{turnServer:null===(t=this.joinInfo)||void 0===t?void 0:t.turnServer});e(this.getJoinMessage({ortc:{iceParameters:i,dtlsParameters:n,rtpCapabilities:r,version:\"2\"}}))})),this.signal.on(_I.REQUEST_REJOIN_INFO,(e=>{e(this.getRejoinMessage())})),this.signal.on(_I.REPORT_JOIN_GATEWAY,((e,t)=>{this.joinInfo&&(eI.joinGateway(this.joinInfo.sid,{lts:this.joinGatewayStartTime,succ:!1,ec:e,addr:t,uid:this.joinInfo.uid,cid:this.joinInfo.cid,firstSuccess:this._isProactiveJoin,avoidJoinStartTime:this.store.avoidJoinStart,isProxy:!!this.joinInfo.proxyServer,signalChannel:this.signal instanceof Dy?\"1\":\"0\"}),this._isProactiveJoin=!1)})),this.signal.on(_I.IS_P2P_DISCONNECTED,(e=>{e(bT(this,XI.IS_P2P_DISCONNECTED))})),this.signal.on(_I.DISCONNECT_P2P,(()=>{this.emit(XI.DISCONNECT_P2P)})),this.signal.on(_I.NEED_RENEW_SESSION,(()=>{this.emit(XI.NEED_RENEW_SESSION)})),this.signal.on(_I.REQUEST_SUCCESS,(()=>{this._signalTimeout=!1})),this.signal.on(_I.REQUEST_TIMEOUT,(()=>{this._signalTimeout=!0})),this.signal.on(_I.JOIN_RESPONSE,(e=>{const t=this.getCurrentGatewayAddress();this.emit(XI.JOIN_RESPONSE,e,t)})),this.signal.on(_I.DATACHANNEL_PRECONNECT,(async(e,t,i)=>{this.updateTurnConfigFromSignal();const n=this.getCurrentGatewayAddress();return vT(this,XI.DATACHANNEL_PRECONNECT,e,n).then(t).catch(i)})),this.signal.on(_I.DATACHANNEL_CONNECTING,(async e=>{const{iceParameters:t,dtlsParameters:i,rtpCapabilities:n}=await vT(this,XI.REQUEST_DC_CONNECTION_PARAMS);e(this.getJoinMessage({ortc:{iceParameters:t,dtlsParameters:i,rtpCapabilities:n,version:\"2\"}}))})),this.signal.on(_I.DATACHANNEL_FAILBACK,(()=>{jC.warning(\"[\".concat(this.store.clientId,\"] User join datachannel failed\")),this.reset(),this.resetSignal(),this.emit(XI.DATACHANNEL_FAILBACK)}))}async tryUnsubBeforeResub(e,t){try{await this.signal.request(EI.UNSUBSCRIBE,{p2p_id:this.store.p2pId,stream_id:e,ortc:[t]},!0)}catch(e){throw jC.warning(\"[\".concat(this.store.clientId,\"] tryUnsubBeforeResub warning\"),e),e}}async tryUnsubDataChannelBeforeResub(e,t){try{await this.signal.request(EI.UNSUBSCRIBE,{stream_id:t.id},!0)}catch(e){throw jC.warning(\"unsubscribe datachannel warning\",e),e}}async tryUnpubBeforeRepub(e,t){try{await this.signal.request(EI.UNPUBLISH,{stream_id:e,ortc:t},!0)}catch(e){throw jC.warning(\"[\".concat(this.store.clientId,\"] tryUnpubBeforeRepub warning: \"),e),e}}async tryUnpubDataChannelBeforeRepub(e,t){try{await this.signal.request(EI.UNPUBLISH_DATASTREAM,{channnel_id:t.channelId},!0)}catch(e){throw jC.warning(\"unpublish datastream warning: \",e),e}}async tryMassUnsubBeforeResub(e){const t={users:e.map((e=>({stream_id:e.stream_id,stream_type:e.stream_type})))};try{await this.signal.request(EI.UNSUBSCRIBE_STREAMS,t,!0)}catch(e){throw jC.warning(\"[\".concat(this.store.clientId,\"] tryMassUnsubBeforeResub warning\"),e),e}}async muteLocal(e,t){const i={action:e.find((e=>e.stream_type===JI.Audio))?\"mute_local_audio\":\"mute_local_video\",p2p_id:this.store.p2pId,ortc:e,stream_id:t};try{await this.signal.request(EI.CONTROL,i,!0,!0)}catch(e){throw jC.warning(\"[\".concat(this.store.clientId,\"] gateway muteLocal warning: \"),e),e}}async unmuteLocal(e,t){const i={action:e.find((e=>e.stream_type===JI.Audio))?\"unmute_local_audio\":\"unmute_local_video\",p2p_id:this.store.p2pId,ortc:e,stream_id:t};try{await this.signal.request(EI.CONTROL,i,!0,!0)}catch(e){throw jC.warning(\"[\".concat(this.store.clientId,\"] gateway unmuteLocal warning: \"),e),e}}async muteRemote(e,t){const i={action:e===av.AUDIO?\"mute_remote_audio\":\"mute_remote_video\",p2p_id:this.store.p2pId,stream_id:t};try{await this.signal.request(EI.CONTROL,i,!0,!0)}catch(e){throw jC.warning(\"[\".concat(this.store.clientId,\"] gateway muteRemote warning: \"),e),e}}async unmuteRemote(e,t){const i={action:e===av.AUDIO?\"unmute_remote_audio\":\"unmute_remote_video\",p2p_id:this.store.p2pId,stream_id:t};try{await this.signal.request(EI.CONTROL,i,!0,!0)}catch(e){throw jC.warning(\"[\".concat(this.store.clientId,\"] gateway unmuteRemote warning: \"),e),e}}uploadWRTCStats(e){this.signal.uploadWRTCStats(e)}upload(e,t){this.signal.upload(e,t)}getSignalRTT(){return this.signal.rtt}async restartICE(e){const t={p2p_id:this.store.p2pId,stream_id:this.store.uid,ortc:e};try{return await this.signal.request(EI.RESTART_ICE,t,!0)}catch(e){throw jC.warning(\"[\".concat(this.store.clientId,\"] P2PChannel.restartICE warning: \"),e),e}}reconnect(){\"CONNECTED\"===this.state&&this.signal.reconnect(void 0,fT.P2P_FAILED)}getCurrentGatewayAddress(){var e;if(!RC(\"GATEWAY_WSS_ADDRESS\"))return null!==(e=this.joinInfo)&&void 0!==e&&e.gatewayAddrs?this.joinInfo.gatewayAddrs[this.signal.currentURLIndex]:void 0}async setPublishAudioFilterEnabled(e){await this.signal.request(EI.SET_PARAMETER,{enablePublishAudioFilter:e})}resetSignal(){this.signal&&(this.signal.removeAllListeners(),this.signal.close(ET.FALLBACK)),this.store.useDataChannel=!1,this.signal=new Jv(My(My({},this.spec),{},{retryConfig:this.spec.websocketRetryConfig}),this.store),this.handleSignalEvents(),this.emit(XI.RESET_SIGNAL,$I.websocket)}}let Vy=0,Fy=0;function By(e,t,i,n){return new cg(((r,s)=>{t.timeout=t.timeout||RC(\"HTTP_CONNECT_TIMEOUT\"),t.responseType=t.responseType||\"json\",t.data&&!i?(t.data=JSON.stringify(t.data),Vy+=$T(t.data)):i&&(t.data.size?Vy+=t.data.size:t.data instanceof FormData?Vy+=eS(t.data):Vy+=$T(JSON.stringify(t.data))),t.headers=t.headers||{},t.headers[\"Content-Type\"]=t.headers[\"Content-Type\"]||\"application/json\",t.method=\"POST\",t.url=e,sC.request(t).then((e=>{\"string\"==typeof e.data?Fy+=$T(e.data):e.data instanceof ArrayBuffer||e.data instanceof Uint8Array?Fy+=e.data.byteLength:Fy+=$T(JSON.stringify(e.data)),n&&r({data:e.data,headers:e.headers}),r(e.data)})).catch((e=>{sC.isCancel(e)?s(new LI(Hg.OPERATION_ABORTED,\"cancel token canceled\")):\"ECONNABORTED\"===e.code?s(new LI(Hg.NETWORK_TIMEOUT,e.message)):e.response?s(new LI(Hg.NETWORK_RESPONSE_ERROR,e.response.status)):s(new LI(Hg.NETWORK_ERROR,e.message))}))}))}\n/*! formdata-polyfill. MIT License. Jimmy W?rting */!function(){var e;function i(e){var t=0;return function(){return t>>0)+\"_\",r=0;return function e(n){if(this instanceof e)throw new TypeError(\"Symbol is not a constructor\");return new t(i+(n||\"\")+\"_\"+r++,n)}})),o(\"Symbol.iterator\",(function(e){if(e)return e;e=Symbol(\"Symbol.iterator\");for(var t=\"Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array\".split(\" \"),r=0;r{const e=RC(\"AREAS\");0===e.length&&e.push(ev.GLOBAL);return BT(e).call(e,((e,t,i)=>{const n=Gy(t);return n?0===i?n:\"\".concat(e,\",\").concat(n):e}),\"\")},Gy=e=>e===ev.OVERSEA?\"\".concat(nv.ASIA,\",\").concat(nv.EUROPE,\",\").concat(nv.AFRICA,\",\").concat(nv.NORTH_AMERICA,\",\").concat(nv.SOUTH_AMERICA,\",\").concat(nv.OCEANIA):nv[e],Wy=e=>{const t={CODE:\"\",WEBCS_DOMAIN:[],WEBCS_DOMAIN_BACKUP_LIST:[],PROXY_CS:[],CDS_AP:[],ACCOUNT_REGISTER:[],UAP_AP:[],EVENT_REPORT_DOMAIN:[],EVENT_REPORT_BACKUP_DOMAIN:[],LOG_UPLOAD_SERVER:[],PROXY_SERVER_TYPE3:[]};return e.map((e=>{const i=rv[e],n=Object.keys(i);n&&n.map((e=>{\"CODE\"!==e&&(t[e]=t[e].concat(i[e]))}))})),t},Hy={GLOBAL:{ASIA:[ev.CHINA,ev.JAPAN,ev.INDIA,ev.KOREA,ev.HKMC],EUROPE:[],NORTH_AMERICA:[ev.US],SOUTH_AMERICA:[],OCEANIA:[],AFRICA:[]}},Ky=Object.keys(Hy[ev.GLOBAL]),Yy=[ev.CHINA,ev.NORTH_AMERICA,ev.EUROPE,ev.ASIA,ev.JAPAN,ev.INDIA,ev.OCEANIA,ev.SOUTH_AMERICA,ev.AFRICA,ev.KOREA,ev.HKMC,ev.US],qy=function(e,t){let i=[];if(bn(e).call(e,ev.GLOBAL)){const s=[ev.GLOBAL,ev.OVERSEA],o=Object.keys(rv);if(t===ev.GLOBAL)throw new LI(Hg.INVALID_PARAMS,\"GLOBAL is an invalid excludedArea value\");if(t===ev.CHINA)i=[ev.OVERSEA];else if(r=t,bn(Ky).call(Ky,r)){const e=(n=t,Hy[ev.GLOBAL][n]||[]),r=[...s,t,...e];i=o.filter((e=>!bn(r).call(r,e)))}else if(function(e){let t=!1;return Ky.forEach((i=>{var n;bn(n=Hy[ev.GLOBAL][i]).call(n,e)&&(t=!0)})),t}(t)){const e=function(e){let t;return Ky.forEach((i=>{var n;bn(n=Hy[ev.GLOBAL][i]).call(n,e)&&(t=i)})),t}(t),n=[...s,e,t];i=o.filter((e=>!bn(n).call(n,e)))}else i=e;i=function(e){const t=[];return Yy.forEach((i=>{bn(e).call(e,i)&&t.push(i)})),t.concat(e.filter((e=>!bn(Yy).call(Yy,e))))}(i)}else i=e;var n,r;return i};function zy(e){var t,i;if(!e&&bn(t=RC(\"AREAS\")).call(t,ev.EXTENSIONS))return jC.debug(\"update area from ap : reset\"),void Jy(tI,!0);if(!bn(i=RC(\"AREAS\")).call(i,ev.GLOBAL)||!e)return;let n=rv.EXTENSIONS;n&&(n={CODE:Gy(ev.EXTENSIONS),WEBCS_DOMAIN:[\"ap-web-1-\".concat(e,\".agora.io\")],WEBCS_DOMAIN_BACKUP_LIST:[\"ap-web-2-\".concat(e,\".ap.sd-rtn.com\")],PROXY_CS:[\"proxy-ap-web-\".concat(e,\".agora.io\")],CDS_AP:[\"cds-ap-web-1-\".concat(e,\".agora.io\"),\"cds-ap-web-2-\".concat(e,\".ap.sd-rtn.com\")],ACCOUNT_REGISTER:[\"sua-ap-web-1-\".concat(e,\".agora.io\"),\"sua-ap-web-2-\".concat(e,\".ap.sd-rtn.com\")],UAP_AP:[\"uap-ap-web-1-\".concat(e,\".agora.io\"),\"uap-ap-web-2-\".concat(e,\".ap.sd-rtn.com\")],EVENT_REPORT_DOMAIN:[\"statscollector-1-\".concat(e,\".agora.io\")],EVENT_REPORT_BACKUP_DOMAIN:[\"statscollector-2-\".concat(e,\".agora.io\")],LOG_UPLOAD_SERVER:[\"logservice-\".concat(e,\".agora.io\")],PROXY_SERVER_TYPE3:[\"webrtc-cloud-proxy-\".concat(e,\".agora.io\")]},jC.debug(\"update area from ap success: \".concat(e,\",config is \"),n),SC(\"AREAS\",[ev.EXTENSIONS],!0),Object.keys(n).map((e=>{if(\"LOG_UPLOAD_SERVER\"===e||\"EVENT_REPORT_DOMAIN\"===e||\"EVENT_REPORT_BACKUP_DOMAIN\"===e||\"PROXY_SERVER_TYPE3\"===e){SC(e,n[e][0])}else SC(e,n[e])})))}function Jy(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const i=eI.reportApiInvoke(null,{name:hT.SET_AREA,options:e,tag:pT.TRACER});try{let n=[];if(\"string\"==typeof e&&(n=[e]),Array.isArray(e)&&(e.forEach((e=>{if(!bn(iv).call(iv,e))throw new LI(Hg.INVALID_PARAMS,\"invalid area code\")})),n=e),\"[object Object]\"===Object.prototype.toString.call(e)){const{areaCode:t,excludedArea:i}=e;if(!t)throw new LI(Hg.INVALID_PARAMS,\"area code is needed\");let r=t;\"string\"==typeof t&&(r=[t]),n=i?qy(r,i):r}if(!t){if(CC.AREAS){const e=new LI(Hg.PROHIBITED_OPERATION,\"setArea is prohibited because of config-distribute\");return i.onError(e),void jC.warning(\"setArea is prohibited because of config-distribute\")}if(bn(n).call(n,ev.GLOBAL)&&RC(\"AREAS\")===ev.EXTENSIONS){const e=new LI(Hg.PROHIBITED_OPERATION,\"setArea is prohibited because of ap extensions\");return i.onError(e),void jC.warning(\"setArea is prohibited because of ap extensions\")}}SC(\"AREAS\",n,t);const r=Wy(n);Object.keys(r).map((e=>{if(\"LOG_UPLOAD_SERVER\"===e||\"EVENT_REPORT_DOMAIN\"===e||\"EVENT_REPORT_BACKUP_DOMAIN\"===e||\"PROXY_SERVER_TYPE3\"===e){SC(e,r[e][0])}else SC(e,r[e])})),jC.debug(\"set area success:\",n.join(\",\"))}catch(e){throw i.onError(e),e}i.onSuccess()}function Xy(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function Qy(e){for(var t=1;t{a=Date.now();const e=await By(d,{data:o,cancelToken:n,headers:{\"X-Packet-Service-Type\":\"0\",\"X-Packet-URI\":\"61\"}});if(c=Date.now()-a,0!==e.code){const t=new LI(Hg.UNEXPECTED_RESPONSE,\"live streaming ap error, code\"+e.code,{retry:!0,responseTime:c});throw jC.error(t.toString()),t}const i=JSON.parse(e.json_body);if(200!==i.code){const e=new LI(Hg.UNEXPECTED_RESPONSE,\"live streaming app center error, code: \".concat(i.code,\", reason: \").concat(i.reason),{code:i.code,responseTime:c});throw jC.error(e.toString()),e}if(!i.servers||0===i.servers.length){const e=new LI(Hg.UNEXPECTED_RESPONSE,\"live streaming app center empty server\",{code:i.code,responseTime:c});throw jC.error(e.toString()),e}const r=function(e,t){return{addressList:e.servers.map((e=>\"wss://\".concat(e.address.replace(/\\./g,\"-\"),\".\").concat(RC(\"WORKER_DOMAIN\"),\":\").concat(e.wss,\"?serviceName=\").concat(encodeURIComponent(t)))),workerToken:e.workerToken,vid:e.vid}}(i,t);return RC(\"LIVE_STREAMING_ADDRESS\")&&(r.addressList=RC(\"LIVE_STREAMING_ADDRESS\")instanceof Array?RC(\"LIVE_STREAMING_ADDRESS\"):[RC(\"LIVE_STREAMING_ADDRESS\")]),Qy(Qy({},r),{},{responseTime:c})}),((n,r)=>(eI.apworkerEvent(i.sid,{success:!0,sc:200,serviceName:t,responseDetail:JSON.stringify(n.addressList),firstSuccess:0===r,responseTime:c,serverIp:e[r%e.length]}),!1)),((n,r)=>(eI.apworkerEvent(i.sid,{success:!1,sc:n.data&&n.data.code||200,serviceName:t,responseTime:c,serverIp:e[r%e.length]}),!!(n.code!==Hg.OPERATION_ABORTED&&n.code!==Hg.UNEXPECTED_RESPONSE||n.data&&n.data.retry)&&(d=e[(r+1)%e.length],!0))),r)}let eA=1;function tA(e,t,i,n){let{url:r,areaCode:s}=e;const o=Date.now();let a;const[c,d]=oA(t,s,[dy.CHOOSE_SERVER]);let l=wT.networkState;return fS((async()=>{l&&wT.networkState===gT.OFFLINE&&wT.onlineWaiter&&await cg.race([wT.onlineWaiter,iS(n&&n.maxRetryTimeout||ES.maxRetryTimeout)]),l=wT.networkState;const{data:e,headers:s}=await By(r,{data:c,cancelToken:i,headers:{\"Content-Type\":\"multipart/form-data;\"}},!0,!0);a=\"1\"===s.http3?1:-1,eI.reportResourceTiming(r,t.sid),nA(e,r,t,o,[dy.CHOOSE_SERVER],a);const d=Iy(e,dy.CHOOSE_SERVER);return rA(d),Ty(d,r)}),(e=>(e&&eI.joinChooseServer(t.sid,{lts:o,succ:!0,csAddr:r,opid:d,serverList:e.gatewayAddrs.map((e=>e.address)),ec:null,cid:e.cid.toString(),uid:e.uid.toString(),csIp:e.csIp,unilbsServerIds:[dy.CHOOSE_SERVER].toString(),isHttp3:a}),!1)),(e=>e.code!==Hg.OPERATION_ABORTED&&(e.code===Hg.CAN_NOT_GET_GATEWAY_SERVER?e.data.retry:(eI.joinChooseServer(t.sid,{lts:o,succ:!1,csAddr:r,serverList:null,opid:d,ec:e.code,csIp:e.data&&e.data.csIp,unilbsServerIds:[dy.CHOOSE_SERVER].toString(),extend:JSON.stringify({networkState:l}),isHttp3:a}),jC.warning(\"[\".concat(t.clientId,\"] Choose server network error, retry\"),e),!0))),n)}function iA(e,t,i,n){let r,{url:s,areaCode:o,serviceIds:a}=e;const c=Date.now(),[d,l]=oA(t,o,a);let u;return fS((async()=>{u&&wT.networkState===gT.OFFLINE&&wT.onlineWaiter&&await cg.race([wT.onlineWaiter,iS(n&&n.maxRetryTimeout||ES.maxRetryTimeout)]),u=wT.networkState;const{data:e,headers:o}=await By(s,{data:d,cancelToken:i,headers:{\"Content-Type\":\"multipart/form-data;\"}},!0,!0);r=\"1\"===o.http3?1:-1,eI.reportResourceTiming(s,t.sid),nA(e,s,t,c,a,r);const l=Iy(e,dy.CHOOSE_SERVER),h=Iy(e,\"proxy5\"===t.cloudProxyServer?dy.CLOUD_PROXY_5:\"proxy3\"===t.cloudProxyServer||\"proxy4\"===t.cloudProxyServer?dy.CLOUD_PROXY:dy.CLOUD_PROXY_FALLBACK);return rA(l),{gatewayInfo:Ty(l,s),proxyInfo:h,url:s}}),(e=>(e.gatewayInfo&&eI.joinChooseServer(t.sid,{lts:c,succ:!0,csAddr:s,serverList:e.gatewayInfo.gatewayAddrs.map((e=>e.address)),ec:null,opid:l,cid:e.gatewayInfo.cid.toString(),uid:e.gatewayInfo.uid.toString(),csIp:e.gatewayInfo.csIp,unilbsServerIds:a.toString(),isHttp3:r}),e.proxyInfo&&eI.joinWebProxyAP(t.sid,{lts:c,sucess:1,apServerAddr:s,turnServerAddrList:e.proxyInfo.addresses.map((e=>e.ip)).join(\",\"),errorCode:null,eventType:t.cloudProxyServer,unilbsServerIds:a.toString()}),!1)),(e=>e.code!==Hg.OPERATION_ABORTED&&(e.code===Hg.CAN_NOT_GET_GATEWAY_SERVER?e.data.retry:(eI.joinWebProxyAP(t.sid,{lts:c,sucess:0,apServerAddr:s,turnServerAddrList:null,errorCode:e.code,eventType:t.cloudProxyServer,unilbsServerIds:a.toString(),extend:JSON.stringify({networkState:u})}),jC.warning(\"[\".concat(t.clientId,\"] multi unilbs network error, retry\"),e),!0))),n)}const nA=(e,t,i,n,r,s)=>{const o=[],a=o=>{4096===o.flag?eI.joinChooseServer(i.sid,{lts:n,succ:!1,csAddr:t,opid:e.opid,serverList:null,ec:o.error.message,csIp:o.error.data&&o.error.data.csIp,unilbsServerIds:r.toString(),isHttp3:s}):1048576!==o.flag&&4194304!==o.flag&&4194310!==o.flag||eI.joinWebProxyAP(i.sid,{lts:n,sucess:0,apServerAddr:t,turnServerAddrList:null,errorCode:o.error.code,eventType:i.cloudProxyServer,unilbsServerIds:r.toString()})};if(e.response_body.forEach((t=>{const i=t.buffer.code;if(23===t.uri&&0===i&&!t.buffer.edges_services)if(4194310===t.buffer.flag)jC.warning(\"no edge services in ap response of proxy fallback, will not set proxy in iceServers\"),t.buffer.edges_services=[];else{const i={error:new LI(Hg.CAN_NOT_GET_GATEWAY_SERVER,\"no edge services in ap response\",{retry:!0,csIp:e.detail[502]}),flag:t.buffer.flag};o.push(i),a(i)}if(0!==i){const n=Pv(i),r={error:new LI(Hg.CAN_NOT_GET_GATEWAY_SERVER,n.desc,{desc:n.desc,retry:n.retry,csIp:e.detail[502]}),flag:t.buffer.flag};4194310===t.buffer.flag?jC.warning(r.error.toString()):o.push(r),a(r)}})),o.length)throw jC.warning(\"[\".concat(i.clientId,\"] multi unilbs \").concat(t,\" failed, \").concat(o.map((e=>\"flag: \".concat(e.flag,\", message: \").concat(e.error.message,\", retry: \").concat(e.error.data.retry))).join(\" | \"))),new LI(Hg.CAN_NOT_GET_GATEWAY_SERVER,o.map((e=>\"flag: \".concat(e.flag,\", message: \").concat(e.error.message))).join(\" | \"),{retry:!!o.find((e=>e.error.data.retry)),csIp:e.detail[502],desc:[...new Set(o.map((e=>{var t;return null==e||null===(t=e.error)||void 0===t||null===(t=t.data)||void 0===t?void 0:t.desc})).filter((e=>!!e)))]})},rA=e=>{var t,i,n,r;if(e.addresses&&0===e.addresses.length&&0===e.code)throw new LI(Hg.CAN_NOT_GET_GATEWAY_SERVER,\"void gateway address\",{retry:!0,csIp:e.detail&&e.detail[502]});RC(\"AP_AREA\")&&(null!==(n=e.detail)&&void 0!==n&&n[23]&&\"string\"==typeof(null===(r=e.detail)||void 0===r?void 0:r[23])?zy(e.detail[23].toLowerCase()):zy());if(null!==(t=e.detail)&&void 0!==t&&t[19]&&\"string\"==typeof(null===(i=e.detail)||void 0===i?void 0:i[19])){const t=e.detail[19],i=null==t?void 0:t.split(\";\");for(let t=0;t0){jC.debug(\"assign gateway address to\",RC(\"GATEWAY_ADDRESS\"));const t=RC(\"GATEWAY_ADDRESS\").map((t=>{var i,n;const r=null!==(i=null===(n=e.addresses.find((e=>e.ip===t.ip&&e.port===t.port)))||void 0===n?void 0:n.fingerprint)&&void 0!==i?i:\"\";return{ip:t.ip,port:t.port,ticket:e.addresses[0]&&e.addresses[0].ticket,fingerprint:r}}));e.addresses=t}},sA=(e,t)=>{if(e.response_body&&e.response_body.length){const t=e.response_body[0];if(0!==t.buffer.code){const e=Pv(t.buffer.code);throw new LI(Hg.UPDATE_TICKET_FAILED,\"[\".concat(t.buffer.code,\"]: \").concat(e.desc),{retry:e.retry})}return t.buffer.ticket}throw jC.debug(\"update ticket request received ap response without response body:\",t),new LI(Hg.UPDATE_TICKET_FAILED,\"cannot find response body from ap response\",{retry:!1})},oA=(e,t,i)=>{const n=Math.floor(Math.random()*10**12),r={appid:e.appId,client_ts:Date.now(),opid:n,sid:e.sid,request_bodies:[{uri:22,buffer:{cname:e.cname,detail:Qy({6:e.stringUid,11:t,12:RC(\"USE_NEW_TOKEN\")?\"1\":void 0,22:t},e.apRTM?{26:\"RTM2\"}:{}),key:e.token,service_ids:i,uid:e.uid||0}}]};r.request_bodies.forEach((t=>{e.multiIP&&e.multiIP.gateway_ip&&(t.buffer.detail[5]=JSON.stringify({vocs_ip:[e.multiIP.uni_lbs_ip],vos_ip:[e.multiIP.gateway_ip]}))}));const s=new FormData;return s.append(\"request\",JSON.stringify(r)),[s,n]},aA=(e,t)=>{const i=Math.floor(Math.random()*10**12),n={appid:e.appId,client_ts:Date.now(),opid:i,sid:e.sid,request_bodies:[{uri:28,buffer:{cname:e.cname,detail:{1:\"\",6:e.stringUid,12:\"1\"},token:e.token,service_ids:t,uid:e.uid||0,edges_services:e.apResponse.addresses.map((e=>({ip:e.ip,port:e.port})))}}]},r=new FormData;return r.append(\"request\",JSON.stringify(n)),[r,i]};let cA=0;function dA(e){return cg.all(e.map((e=>e.then((e=>{throw e}),(e=>e))))).then((e=>{throw e}),(e=>e))}const lA=async e=>{let{fragementLength:t,referenceList:i,asyncMapHandler:n,allFailedhandler:r,promisesCollector:s}=e,o=0;const a=t;let c,d=0;const l=async()=>{const e=(()=>{const e=o*a,t=e+a;return i.slice(e,t).map(n)})();s&&s.push(...e);try{c=await dA(e)}catch(e){if(d+=a,o++,!(d>=i.length))return void await l();r(e)}e.forEach((e=>e.cancel()))};return await l(),c};async function uA(e,t,i,n){const r=async function(e,t,i,n){let r=null;const s=[],o=async()=>{const r=RC(\"WEBCS_DOMAIN\").slice(0,RC(\"AJAX_REQUEST_CONCURRENT\")).map((t=>({url:e.proxyServer?\"https://\".concat(e.proxyServer,\"/ap/?url=\").concat(t+\"/api/v2/transpond/webrtc?v=2\"):\"https://\".concat(t,\"/api/v2/transpond/webrtc?v=2\"),areaCode:jy()}))),o=n.recordJoinChannelService({startTs:Date.now(),status:\"pending\",service:\"chooseServer\",urls:r.map((e=>e.url))}),a=await lA({fragementLength:RC(\"FRAGEMENT_LENGTH\"),referenceList:r,asyncMapHandler:n=>(jC.debug(\"[\".concat(e.clientId,\"] Connect to choose_server:\"),n.url),tA(n,e,t,i)),allFailedhandler:e=>{throw n.recordJoinChannelService({endTs:Date.now(),status:\"error\",errors:e},o),e[0]},promisesCollector:s});return n.recordJoinChannelService({endTs:Date.now(),status:\"success\"},o),a},a=async()=>{if(await iS(1e3),null!==r)return r;const o=RC(\"WEBCS_DOMAIN_BACKUP_LIST\").map((t=>({url:e.proxyServer?\"https://\".concat(e.proxyServer,\"/ap/?url=\").concat(t+\"/api/v2/transpond/webrtc?v=2\"):\"https://\".concat(t,\"/api/v2/transpond/webrtc?v=2\"),areaCode:jy()}))),a=n.recordJoinChannelService({endTs:void 0,startTs:Date.now(),status:\"pending\",service:\"chooseServer\",urls:o.map((e=>e.url))}),c=await lA({fragementLength:RC(\"FRAGEMENT_LENGTH\"),referenceList:o,asyncMapHandler:n=>(jC.debug(\"[\".concat(e.clientId,\"] Connect to backup choose_server:\"),n.url),tA(n,e,t,i)),allFailedhandler:e=>{throw n.recordJoinChannelService({endTs:Date.now(),status:\"error\",errors:e},a),e[0]},promisesCollector:s});return n.recordJoinChannelService({endTs:Date.now(),status:\"success\"},a),c};try{return r=await dA([o(),a()]),s.length&&s.forEach((e=>e.cancel&&\"function\"==typeof e.cancel&&e.cancel())),r}catch(e){throw e[0]}}(e,t,i,n);return{gatewayInfo:await r}}async function hA(e,t,i,n,r){const s=e.cloudProxyServer;if(\"disabled\"===s){if(!n)return;if(e.useLocalAccessPoint)return await uA(e,t,i,r);if(RC(\"JOIN_WITH_FALLBACK_MEDIA_PROXY\")){const{gatewayInfo:n,proxyInfo:s}=await EA(e,t,i,r);if(e.turnServer&&\"auto\"!==e.turnServer.mode)return{gatewayInfo:n};const a=s.map((e=>({turnServerURL:e.address,tcpport:e.tcpport||iI.tcpport,udpport:e.udpport||iI.udpport,username:e.username||iI.username,password:e.password||iI.password,forceturn:!1,security:!0})));if(r.useP2P){var o;const t=null!==(o=e.uid)&&void 0!==o?o:n.uid,i=\"glb:\".concat(t.toString()),r=await cT(i),c=s.map((e=>({turnServerURL:e.address,tcpport:e.tcpport||iI.tcpport,udpport:e.udpport||iI.udpport,username:i,password:r,forceturn:!1,security:!0})));a.push(...c)}return e.turnServer={mode:\"manual\",servers:a},{gatewayInfo:n}}return await uA(e,t,i,r)}const{proxyInfo:a,gatewayInfo:c}=await EA(e,t,i,r),d={gatewayInfo:c},l=a.map((e=>({turnServerURL:e.address,tcpport:\"proxy3\"===s?void 0:e.tcpport?e.tcpport:iI.tcpport,udpport:\"proxy4\"===s?void 0:e.udpport?e.udpport:iI.udpport,username:e.username||iI.username,password:e.password||iI.password,forceturn:\"proxy4\"!==s,security:\"proxy5\"===s})));if(r.useP2P){var u;const t=null!==(u=e.uid)&&void 0!==u?u:c.uid,i=\"glb:\".concat(t.toString()),n=await cT(i),r=a.map((e=>({turnServerURL:e.address,tcpport:\"proxy3\"===s?void 0:e.tcpport||iI.tcpport,udpport:\"proxy4\"===s?void 0:e.udpport||iI.udpport,username:i,password:n,forceturn:\"proxy4\"!==s,security:\"proxy5\"===s})));l.push(...r)}return e.turnServer={mode:\"manual\",servers:l},jC.debug(\"[\".concat(e.clientId,\"] set proxy server: \").concat(e.proxyServer,\", mode: \").concat(s)),d}async function pA(e,t,i,n,r){const s=RC(\"ACCOUNT_REGISTER\").slice(0,RC(\"AJAX_REQUEST_CONCURRENT\"));let o=[];o=t.proxyServer?s.map((e=>\"https://\".concat(t.proxyServer,\"/ap/?url=\").concat(e+\"/api/v1\"))):s.map((e=>\"https://\".concat(e,\"/api/v1\")));const a=null==r?void 0:r.recordJoinChannelService({startTs:Date.now(),status:\"pending\",service:\"stringUID\",urls:o});try{const s=await async function(e,t,i,n,r){const s=Date.now(),o={sid:i.sid,opid:10,appid:i.appId,string_uid:t};let a=e[0];const c=await fS((()=>By(a+\"\".concat(-1===a.indexOf(\"?\")?\"?\":\"&\",\"action=stringuid\"),{data:o,cancelToken:n,headers:{\"X-Packet-Service-Type\":0,\"X-Packet-URI\":72}})),((i,n)=>{if(0===i.code){if(i.uid<=0||i.uid>=Math.pow(2,32))throw jC.error(\"Invalid Uint Uid \".concat(t,\" => \").concat(i.uid),i),eI.reqUserAccount(o.sid,{lts:s,success:!1,serverAddr:a,stringUid:o.string_uid,uid:i.uid,errorCode:Hg.INVALID_UINT_UID_FROM_STRING_UID,extend:o}),new LI(Hg.INVALID_UINT_UID_FROM_STRING_UID);return eI.reqUserAccount(o.sid,{lts:s,success:!0,serverAddr:a,stringUid:o.string_uid,uid:i.uid,errorCode:null,extend:o}),!1}const r=Pv(i.code);return r.retry&&(a=e[(n+1)%e.length]),eI.reqUserAccount(o.sid,{lts:s,success:!1,serverAddr:a,stringUid:o.string_uid,uid:i.uid,errorCode:r.desc,extend:o}),r.retry}),((t,i)=>t.code!==Hg.OPERATION_ABORTED&&(eI.reqUserAccount(o.sid,{lts:s,success:!1,serverAddr:a,stringUid:o.string_uid,uid:null,errorCode:t.code,extend:o}),a=e[(i+1)%e.length],!0)),r);if(0!==c.code){const e=Pv(c.code);throw new LI(Hg.UNEXPECTED_RESPONSE,e.desc)}return c}(o,e,t,i,n);return null==r||r.recordJoinChannelService({status:\"success\",endTs:Date.now()},a),s.uid}catch(e){throw null==r||r.recordJoinChannelService({status:\"error\",endTs:Date.now(),errors:[e]},a),e}}async function _A(e,t,i){const n=RC(\"CDS_AP\").slice(0,RC(\"AJAX_REQUEST_CONCURRENT\")).map((t=>e.proxyServer?\"https://\".concat(e.proxyServer,\"/ap/?url=\").concat(t+\"/api/v1\"):\"https://\".concat(t,\"/api/v1?action=config\"))),r=n.map((n=>function(e,t,i,n){const r=Sg(),s={flag:64,cipher_method:0,features:{device:r.name,system:r.os,system_general:navigator.userAgent,vendor:t.appId,version:EC,cname:t.cname,sid:t.sid,session_id:t.sid,detail:\"\",proxyServer:t.proxyServer}};return fS((()=>By(e,{data:s,timeout:1e3,cancelToken:i,headers:{\"X-Packet-Service-Type\":0,\"X-Packet-URI\":54}})),void 0,(e=>e.code!==Hg.OPERATION_ABORTED),n)}(n,e,t,i)));let s=null,o=null,a={};try{s=await dA(r)}catch(e){if(e.code===Hg.OPERATION_ABORTED)throw e;o=e}r.forEach((e=>e.cancel()));if(eI.reportApiInvoke(e.sid,{name:hT.REQUEST_CONFIG_DISTRIBUTE,options:{error:o,res:s}}).onSuccess(),s&&s.test_tags)try{a=function(e){if(!e.test_tags)return{};const t=e.test_tags,i=Object.keys(t),n={};return i.forEach((e=>{var i;const r=Ey(i=e.slice(4)).call(i),s=JSON.parse(t[e])[1];n[r]=s})),n}(s)}catch(e){}return a}async function EA(e,t,i,n){const r=RC(\"PROXY_SERVER_TYPE3\"),s=(e,t,i)=>{let n=i||r;return Array.isArray(n)&&(n=t%2==0?r[1]:r[0]),\"https://\".concat(n,\"/ap/?url=\").concat(e)};let o=null;const a=[],c=async()=>{const r=RC(\"WEBCS_DOMAIN\").slice(0,RC(\"AJAX_REQUEST_CONCURRENT\")).map(((t,i)=>{let n;return n=\"disabled\"===e.cloudProxyServer&&e.proxyServer?s(\"\".concat(t,\"/api/v2/transpond/webrtc?v=2\"),i,e.proxyServer):\"disabled\"===e.cloudProxyServer||\"fallback\"===e.cloudProxyServer?\"https://\".concat(t,\"/api/v2/transpond/webrtc?v=2\"):s(\"\".concat(t,\"/api/v2/transpond/webrtc?v=2\"),i),{url:n,areaCode:jy(),serviceIds:[dy.CHOOSE_SERVER,\"proxy5\"===e.cloudProxyServer?dy.CLOUD_PROXY_5:\"proxy3\"===e.cloudProxyServer||\"proxy4\"===e.cloudProxyServer?dy.CLOUD_PROXY:dy.CLOUD_PROXY_FALLBACK]}})),o=n.recordJoinChannelService({startTs:Date.now(),status:\"pending\",service:\"chooseServer\",urls:r.map((e=>e.url))}),c=await lA({fragementLength:RC(\"FRAGEMENT_LENGTH\"),referenceList:r,asyncMapHandler:n=>(jC.debug(\"[\".concat(e.clientId,\"] Connect to choose_server:\"),n.url),iA(n,e,t,i)),allFailedhandler:e=>{throw n.recordJoinChannelService({endTs:Date.now(),status:\"error\",errors:e},o),e[0]},promisesCollector:a});return n.recordJoinChannelService({endTs:Date.now(),status:\"success\"},o),c},d=async()=>{if(await iS(1e3),null!==o)return o;const r=RC(\"WEBCS_DOMAIN_BACKUP_LIST\").map(((t,i)=>{let n;return n=\"disabled\"===e.cloudProxyServer&&e.proxyServer?s(\"\".concat(t,\"/api/v2/transpond/webrtc?v=2\"),i,e.proxyServer):\"disabled\"===e.cloudProxyServer||\"fallback\"===e.cloudProxyServer?\"https://\".concat(t,\"/api/v2/transpond/webrtc?v=2\"):s(\"\".concat(t,\"/api/v2/transpond/webrtc?v=2\"),i),{url:n,areaCode:jy(),serviceIds:[dy.CHOOSE_SERVER,\"proxy5\"===e.cloudProxyServer?dy.CLOUD_PROXY_5:\"proxy3\"===e.cloudProxyServer||\"proxy4\"===e.cloudProxyServer?dy.CLOUD_PROXY:dy.CLOUD_PROXY_FALLBACK]}})),c=n.recordJoinChannelService({startTs:Date.now(),status:\"pending\",service:\"chooseServer\",urls:r.map((e=>e.url))}),d=await lA({fragementLength:RC(\"FRAGEMENT_LENGTH\"),referenceList:r,asyncMapHandler:n=>(jC.debug(\"[\".concat(e.clientId,\"] Connect to backup choose_server:\"),n.url),iA(n,e,t,i)),allFailedhandler:e=>{throw n.recordJoinChannelService({endTs:Date.now(),status:\"error\",errors:e},c),e[0]},promisesCollector:a});return n.recordJoinChannelService({endTs:Date.now(),status:\"success\"},c),d};let l,u,h;try{({gatewayInfo:l,proxyInfo:u,url:h}=await dA([c(),d()]))}catch(e){throw e[0]}if(a.length&&a.forEach((e=>e.cancel&&\"function\"==typeof e.cancel&&e.cancel())),!l||!u)throw new LI(Hg.UNEXPECTED_ERROR,\"missing gateway or proxy response\").print();if(e.apUrl=h,\"disabled\"!==e.cloudProxyServer&&Array.isArray(r)&&h){const t=/^https?:\\/\\/(.+?)(\\/.*)?$/.exec(h)[1];bn(r).call(r,t)&&(e.proxyServer=t,jC.setProxyServer(t),eI.setProxyServer(t))}return o={gatewayInfo:l,proxyInfo:await vy(u,l.uid)},o}async function mA(e,t,i,n){const r=RC(\"UAP_AP\").slice(0,RC(\"AJAX_REQUEST_CONCURRENT\")).map((e=>t.proxyServer?\"https://\".concat(t.proxyServer,\"/ap/?url=\").concat(e+\"/api/v1?action=uap\"):\"https://\".concat(e,\"/api/v1?action=uap\")));return await $y(r,e,t,i,n)}async function fA(e,t,i){const n=RC(\"UAP_AP\").slice(0,RC(\"AJAX_REQUEST_CONCURRENT\")).map((t=>e.proxyServer?\"https://\".concat(e.proxyServer,\"/ap/?url=\").concat(t+\"/api/v1?action=uap\"):\"https://\".concat(t,\"/api/v1?action=uap\"))),r=n.map((n=>function(e,t,i,n){const r={command:\"convergeAllocateEdge\",sid:t.sid,appId:t.appId,token:t.token,ts:Date.now(),version:EC,cname:t.cname,uid:t.uid.toString(),requestId:eA,seq:eA};eA+=1;const s={service_name:\"tele_channel\",json_body:JSON.stringify(r)};return fS((async()=>{const t=await By(e,{data:s,cancelToken:i,headers:{\"X-Packet-Service-Type\":0,\"X-Packet-URI\":61}});if(0!==t.code){const e=new LI(Hg.UNEXPECTED_RESPONSE,\"cross channel ap error, code\"+t.code,{retry:!0});throw jC.error(e.toString()),e}const n=JSON.parse(t.json_body);if(200!==n.code){const e=new LI(Hg.UNEXPECTED_RESPONSE,\"cross channel app center error, code: \".concat(n.code,\", reason: \").concat(n.reason));throw jC.error(e.toString()),e}if(!n.servers||0===n.servers.length){const e=new LI(Hg.UNEXPECTED_RESPONSE,\"cross channel app center empty server\");throw jC.error(e.toString()),e}return{vid:n.vid,workerToken:n.workerToken,addressList:(RC(\"CHANNEL_MEDIA_RELAY_SERVERS\")||n.servers).map((e=>\"wss://\".concat(e.address.replace(/\\./g,\"-\"),\".\").concat(RC(\"WORKER_DOMAIN\"),\":\").concat(e.wss)))}}),void 0,(e=>!!(e.code!==Hg.OPERATION_ABORTED&&e.code!==Hg.UNEXPECTED_RESPONSE||e.data&&e.data.retry)),n)}(n,e,t,i)));try{const e=await dA(r);return r.forEach((e=>e.cancel())),e}catch(e){throw e[0]}}async function gA(e,t,i){let n=null;const r=[],s=async s=>{const o=RC(s?\"WEBCS_DOMAIN_BACKUP_LIST\":\"WEBCS_DOMAIN\").map((t=>e.proxyServer?\"https://\".concat(e.proxyServer,\"/ap/?url=\").concat(t+\"/api/v2/transpond/webrtc?v=2\"):\"https://\".concat(t,\"/api/v2/transpond/webrtc?v=2\")));return s&&(await iS(1e3),null!==n)?n:await lA({fragementLength:RC(\"FRAGEMENT_LENGTH\"),referenceList:o,asyncMapHandler:n=>(jC.debug(\"[\".concat(e.clientId,\"] update ticket, Connect to \").concat(s?\"backup\":\"\",\" choose_server:\"),n),function(e,t,i,n){const[r]=aA(t,[dy.CHOOSE_SERVER]);let s=wT.networkState;return fS((async()=>{s&&wT.networkState===gT.OFFLINE&&wT.onlineWaiter&&await cg.race([wT.onlineWaiter,iS(n&&n.maxRetryTimeout||ES.maxRetryTimeout)]),s=wT.networkState;const t=await By(e,{data:r,cancelToken:i,headers:{\"Content-Type\":\"multipart/form-data;\"}},!0);return sA(t,e)}),(()=>!1),(e=>e.code!==Hg.OPERATION_ABORTED&&(e.code===Hg.UPDATE_TICKET_FAILED?e.data.retry:(jC.warning(\"[\".concat(t.clientId,\"] update ticket network error, retry\"),e),!0))),n)}(n,e,t,i)),allFailedhandler:e=>{throw e[0]},promisesCollector:r})};try{return n=await dA([s(!1),s(!0)]),r.length&&r.forEach((e=>e.cancel&&\"function\"==typeof e.cancel&&e.cancel())),n}catch(e){throw e[0]}}function TA(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function SA(e){for(var t=1;t{this.updateConfigDistribute()}),RC(\"CONFIG_DISTRIBUTE_INTERVAL\")))}stopGetConfigDistribute(){this.interval&&clearInterval(this.interval),this.interval=void 0,this.joinInfo=void 0,this.cancelToken=void 0}async awaitConfigDistributeComplete(){if(!this.mutex.isLocked)return;(await this.mutex.lock())()}async updateConfigDistribute(){if(!this.mutableParamsRead){this.mutableParamsRead=!0;eI.reportApiInvoke(null,{options:void 0,name:hT.LOAD_CONFIG_FROM_LOCALSTORAGE,tag:pT.TRACER}).onSuccess(JSON.stringify(CC))}if(!this.joinInfo||!this.cancelToken||!this.retryConfig)return void jC.debug(\"[config-distribute] get config distribute interrupted have no joininfo\");let e;const t=await this.mutex.lock();try{e=await _A(this.joinInfo,this.cancelToken,this.retryConfig),jC.debug(\"[config-distribute] get config distribute\",JSON.stringify(e)),e.limit_bitrate&&this.handleBitrateLimit(e.limit_bitrate),this.cacheGlobalParameterConfig(e),this.configs=e}catch(e){const t=new LI(Hg.NETWORK_RESPONSE_ERROR,e);jC.warning(\"[config-distribute] \".concat(t.toString()))}finally{t()}}getBitrateLimit(){return this.configs?this.configs.limit_bitrate:void 0}handleBitrateLimit(e){var t;(t=e)&&t.uplink&&t.id&&void 0!==t.uplink.max_bitrate&&void 0!==t.uplink.min_bitrate&&(this.configs&&this.configs.limit_bitrate?this.configs&&this.configs.limit_bitrate&&this.configs.limit_bitrate.id!==e.id&&this.emit(sv.UPDATE_BITRATE_LIMIT,e):this.emit(sv.UPDATE_BITRATE_LIMIT,e))}getLowStreamConfigDistribute(){return this.configs&&this.configs.limit_bitrate&&SA({},this.configs.limit_bitrate.low_stream_uplink)}cacheGlobalParameterConfig(e){var t;const i=ep(t=Object.keys(e).filter((e=>/^webrtc_ng_global_parameter/.test(e)))).call(t);for(let t=0;tt;n--){const t=i[n];if(\"number\"==typeof e[t].__priority){const r=e[t].__priority,s=i[n-1];if(\"number\"==typeof e[s].__priority){if(!(r>e[s].__priority))continue;{const e=t;i[n]=i[n-1],i[n-1]=e}}else{const e=t;i[n]=i[n-1],i[n-1]=e}}}const n={};i.forEach((t=>{const i=e[t],r=i.__expires;Object.keys(i).forEach((e=>{\"__priority\"===e||\"__expires\"===e||Object.prototype.hasOwnProperty.call(n,e)||(n[e]=SA({value:i[e]},r&&{expires:r}))}))}));try{!function(e){try{const t=Date.now();Object.keys(e).forEach((i=>{switch(i){case\"ENABLE_EVENT_REPORT\":case\"UPLOAD_LOG\":if(Object.prototype.hasOwnProperty.call(TC,i)){const{value:n,expires:r}=e[i];if(r&&r<=t)return;CC[i]=n,TC[i]=n,jC.debug(\"Update global parameters from config distribute\",i,n)}}}))}catch(t){jC.error(\"Error update config immediately: \".concat(e),t.message)}}(n);const e=JSON.stringify(n),t=window.btoa(e);window.localStorage.setItem(\"websdk_ng_global_parameter\",t),jC.debug(\"Caching global parameters \".concat(e))}catch(e){jC.error(\"Error caching global parameters:\",e.message)}}}const CA={getDisplayMedia:!1,getStreamFromExtension:!1,supportUnifiedPlan:!1,supportMinBitrate:!1,supportSetRtpSenderParameters:!1,supportDualStream:!0,webAudioMediaStreamDest:!1,supportReplaceTrack:!1,supportWebGL:!1,webAudioWithAEC:!1,supportRequestFrame:!1,supportShareAudio:!1,supportDualStreamEncoding:!1,supportDataChannel:!1,supportPCSetConfiguration:!1,supportWebRTCEncodedTransform:!1,supportWebRTCInsertableStream:!1};function IA(){return CA}var vA;function yA(e,t,i){return{sampleRate:e,stereo:t,bitrate:i}}function AA(e,t,i,n,r){return{width:e,height:t,frameRate:i,bitrateMin:n,bitrateMax:r}}function bA(e,t,i,n,r){return{width:{max:e},height:{max:t},frameRate:i,bitrateMin:n,bitrateMax:r}}function wA(e,t){return{numSpatialLayers:e,numTemporalLayers:t}}!function(e){e.IOS_15_16_INTERRUPTION_START=\"ios15_16-interruption-start\",e.IOS_15_16_INTERRUPTION_END=\"ios15_16-interruption-end\",e.IOS_INTERRUPTION_START=\"ios-interruption-start\",e.IOS_INTERRUPTION_END=\"ios-interruption-end\",e.STATE_CHANGE=\"state-change\"}(vA||(vA={}));const OA={\"90p\":AA(160,90),\"90p_1\":AA(160,90),\"120p\":AA(160,120,15,30,65),\"120p_1\":AA(160,120,15,30,65),\"120p_3\":AA(120,120,15,30,50),\"120p_4\":AA(212,120),\"180p\":AA(320,180,15,30,140),\"180p_1\":AA(320,180,15,30,140),\"180p_3\":AA(180,180,15,30,100),\"180p_4\":AA(240,180,15,30,120),\"240p\":AA(320,240,15,40,200),\"240p_1\":AA(320,240,15,40,200),\"240p_3\":AA(240,240,15,40,140),\"240p_4\":AA(424,240,15,40,220),\"360p\":AA(640,360,15,80,400),\"360p_1\":AA(640,360,15,80,400),\"360p_3\":AA(360,360,15,80,260),\"360p_4\":AA(640,360,30,80,600),\"360p_6\":AA(360,360,30,80,400),\"360p_7\":AA(480,360,15,80,320),\"360p_8\":AA(480,360,30,80,490),\"360p_9\":AA(640,360,15,80,800),\"360p_10\":AA(640,360,24,80,800),\"360p_11\":AA(640,360,24,80,1e3),\"480p\":AA(640,480,15,100,500),\"480p_1\":AA(640,480,15,100,500),\"480p_2\":AA(640,480,30,100,1e3),\"480p_3\":AA(480,480,15,100,400),\"480p_4\":AA(640,480,30,100,750),\"480p_6\":AA(480,480,30,100,600),\"480p_8\":AA(848,480,15,100,610),\"480p_9\":AA(848,480,30,100,930),\"480p_10\":AA(640,480,10,100,400),\"720p\":AA(1280,720,15,120,1130),\"720p_auto\":AA(1280,720,30,900,3e3),\"720p_1\":AA(1280,720,15,120,1130),\"720p_2\":AA(1280,720,30,120,2e3),\"720p_3\":AA(1280,720,30,120,1710),\"720p_5\":AA(960,720,15,120,910),\"720p_6\":AA(960,720,30,120,1380),\"1080p\":AA(1920,1080,15,120,2080),\"1080p_1\":AA(1920,1080,15,120,2080),\"1080p_2\":AA(1920,1080,30,120,3e3),\"1080p_3\":AA(1920,1080,30,120,3150),\"1080p_5\":AA(1920,1080,60,120,4780),\"1440p\":AA(2560,1440,30,120,4850),\"1440p_1\":AA(2560,1440,30,120,4850),\"1440p_2\":AA(2560,1440,60,120,7350),\"4k\":AA(3840,2160,30,120,8910),\"4k_1\":AA(3840,2160,30,120,8910),\"4k_3\":AA(3840,2160,60,120,13500)},NA=[{scaleResolutionDownBy:2,width:1280,height:720,frameRate:30,bitrateMin:300,bitrateMax:900},{scaleResolutionDownBy:1.333333,width:1280,height:720,frameRate:30,bitrateMin:600,bitrateMax:2e3},{scaleResolutionDownBy:1,width:1280,height:720,frameRate:30,bitrateMin:900,bitrateMax:3e3}],DA={\"480p\":bA(640,480,5),\"480p_1\":bA(640,480,5),\"480p_2\":bA(640,480,30),\"480p_3\":bA(640,480,15),\"720p\":bA(1280,720,5),\"720p_auto\":AA(1280,720,30,900,3e3),\"720p_1\":bA(1280,720,5),\"720p_2\":bA(1280,720,30),\"720p_3\":bA(1280,720,15),\"1080p\":bA(1920,1080,5),\"1080p_1\":bA(1920,1080,5),\"1080p_2\":bA(1920,1080,30),\"1080p_3\":bA(1920,1080,15)},PA={\"1SL1TL\":wA(1,1),\"3SL3TL\":wA(3,3),\"2SL3TL\":wA(2,3)};function LA(e){return e||(e=\"480p_1\"),\"string\"==typeof e?Object.assign({},OA[e]):e}function kA(e){return\"string\"==typeof e?Object.assign({},DA[e]):e}function MA(e){return\"string\"==typeof e?Object.assign({},PA[e]):e}const UA={speech_low_quality:yA(16e3,!1),speech_standard:yA(32e3,!1,18),music_standard:yA(48e3,!1),standard_stereo:yA(48e3,!0,56),high_quality:yA(48e3,!1,128),high_quality_stereo:yA(48e3,!0,192)};function xA(e){return\"string\"==typeof e?Object.assign({},UA[e]):e}const VA=[];function FA(e){return qg(e,\"mediaSource\",[\"screen\",\"window\",\"application\"]),!0}var BA,jA,GA,WA,HA,KA,YA,qA,zA,JA;!function(e){e.NEED_RENEGOTIATE=\"@need_renegotiate\",e.NEED_REPLACE_TRACK=\"@need_replace_track\",e.NEED_REPLACE_MIXING_TRACK=\"@need_replace_mixing_track\",e.NEED_CLOSE=\"@need_close\",e.NEED_ENABLE_TRACK=\"@need_enable_track\",e.NEED_DISABLE_TRACK=\"@need_disable_track\",e.NEED_SESSION_ID=\"@need_sid\",e.SET_OPTIMIZATION_MODE=\"@set_optimization_mode\",e.GET_STATS=\"@get_stats\",e.GET_RTC_STATS=\"@get_rtc_stats\",e.GET_LOW_VIDEO_TRACK=\"@get_low_video_track\",e.NEED_RESET_REMOTE_SDP=\"@need_reset_remote_sdp\",e.NEED_UPDATE_VIDEO_ENCODER=\"@need_update_video_encoder\",e.NEED_MUTE_TRACK=\"@need_mute_track\",e.NEED_UNMUTE_TRACK=\"@need_unmute_track\"}(BA||(BA={})),function(e){e.SCREEN_TRACK=\"screen_track\",e.CUSTOM_TRACK=\"custome_track\",e.LOW_STREAM=\"low_stream\"}(jA||(jA={})),function(e){e[e.HIGH_STREAM=0]=\"HIGH_STREAM\",e[e.LOW_STREAM=1]=\"LOW_STREAM\"}(GA||(GA={})),function(e){e[e.HIGH_STREAM=0]=\"HIGH_STREAM\",e[e.LOW_STREAM=1]=\"LOW_STREAM\"}(WA||(WA={})),function(e){e[e.DISABLE=0]=\"DISABLE\",e[e.LOW_STREAM=1]=\"LOW_STREAM\",e[e.AUDIO_ONLY=2]=\"AUDIO_ONLY\"}(HA||(HA={})),function(e){e.TRANSCEIVER_UPDATED=\"transceiver-updated\",e.SEI_TO_SEND=\"sei-to-send\",e.SEI_RECEIVED=\"sei-received\"}(KA||(KA={})),function(e){e.SOURCE_STATE_CHANGE=\"source-state-change\",e.TRACK_ENDED=\"track-ended\",e.BEAUTY_EFFECT_OVERLOAD=\"beauty-effect-overload\",e.VIDEO_ELEMENT_VISIBLE_STATUS=\"video-element-visible-status\",e.CLOSED=\"closed\"}(YA||(YA={})),function(e){e.FIRST_FRAME_DECODED=\"first-frame-decoded\",e.VIDEO_ELEMENT_VISIBLE_STATUS=\"video-element-visible-status\",e.VIDEO_STATE_CHANGED=\"video-state-changed\"}(qA||(qA={})),function(e){e.AUDIO_SOURCE_STATE_CHANGE=\"audio_source_state_change\",e.RECEIVE_TRACK_BUFFER=\"receive_track_buffer\",e.ON_AUDIO_BUFFER=\"on_audio_buffer\",e.UPDATE_SOURCE=\"update_source\"}(zA||(zA={})),function(e){e.UPDATE_TRACK_SOURCE=\"update-track-source\"}(JA||(JA={}));const XA={sendVolumeLevel:0,sendBitrate:0,sendBytes:0,sendPackets:0,sendPacketsLost:0,sendJitterMs:0,sendRttMs:0,currentPacketLossRate:0},QA={sendBytes:0,sendBitrate:0,sendPackets:0,sendPacketsLost:0,sendJitterMs:0,sendRttMs:0,sendResolutionHeight:0,sendResolutionWidth:0,captureResolutionHeight:0,captureResolutionWidth:0,targetSendBitrate:0,totalDuration:0,totalFreezeTime:0,currentPacketLossRate:0},ZA={transportDelay:0,end2EndDelay:0,receiveBitrate:0,receiveLevel:0,receiveBytes:0,receiveDelay:0,receivePackets:0,receivePacketsLost:0,totalDuration:0,totalFreezeTime:0,freezeRate:0,packetLossRate:0,currentPacketLossRate:0,publishDuration:-1},$A={uplinkNetworkQuality:0,downlinkNetworkQuality:0},eb={transportDelay:0,end2EndDelay:0,receiveBitrate:0,receiveBytes:0,receiveDelay:0,receivePackets:0,receivePacketsLost:0,receiveResolutionHeight:0,receiveResolutionWidth:0,totalDuration:0,totalFreezeTime:0,freezeRate:0,packetLossRate:0,currentPacketLossRate:0,publishDuration:-1};var tb,ib,nb,rb,sb,ob;!function(e){e.ON_TRACK=\"on_track\",e.ON_NODE=\"on_node\"}(tb||(tb={})),function(e){e.REQUEST_UPDATE_CONSTRAINTS=\"request_update_constraints\",e.REQUEST_CONSTRAINTS=\"request_constraints\"}(ib||(ib={})),function(e){e.IDLE=\"IDLE\",e.INITING=\"INITING\",e.INITEND=\"INITEND\"}(nb||(nb={})),function(e){e.STATE_CHANGE=\"state_change\",e.RECORDING_DEVICE_CHANGED=\"recordingDeviceChanged\",e.PLAYOUT_DEVICE_CHANGED=\"playoutDeviceChanged\",e.CAMERA_DEVICE_CHANGED=\"cameraDeviceChanged\"}(rb||(rb={})),function(e){e.NONE=\"none\",e.INIT=\"init\",e.CANPLAY=\"canplay\",e.PLAYING=\"playing\",e.PAUSED=\"paused\",e.SUSPEND=\"suspend\",e.STALLED=\"stalled\",e.WAITING=\"waiting\",e.ERROR=\"error\",e.DESTROYED=\"destroyed\",e.ABORT=\"abort\",e.ENDED=\"ended\",e.EMPTIED=\"emptied\",e.LOADEDDATA=\"loadeddata\"}(sb||(sb={})),function(e){e[e.VideoStateStopped=0]=\"VideoStateStopped\",e[e.VideoStateStarting=1]=\"VideoStateStarting\",e[e.VideoStateDecoding=2]=\"VideoStateDecoding\",e[e.VideoStateFrozen=3]=\"VideoStateFrozen\"}(ob||(ob={}));const ab={uninit:100,none:110,init:120,loadeddata:130,canplay:200,playing:210,paused:220,suspend:300,stalled:310,waiting:320,error:330,destroyed:340,abort:350,ended:360,emptied:370};var cb;!function(e){e.OPEN=\"open\",e.MESSAGE=\"message\",e.CLOSE=\"close\",e.CLOSING=\"closing\",e.ERROR=\"error\"}(cb||(cb={}));class db extends dT{constructor(e,t){super(),sh(this,\"_ID\",void 0),sh(this,\"_rtpTransceiver\",void 0),sh(this,\"_lowRtpTransceiver\",void 0),sh(this,\"_hints\",[]),sh(this,\"_isClosed\",!1),sh(this,\"_originMediaStreamTrack\",void 0),sh(this,\"_mediaStreamTrack\",void 0),sh(this,\"_external\",{}),this._ID=t||nS(8,\"track-\"),this._originMediaStreamTrack=e,this._mediaStreamTrack=e,function(e){bn(VA).call(VA,e)||VA.push(e)}(this)}toString(){return this._ID}getTrackId(){return this._ID}getMediaStreamTrack(e){if(!e){const e=eI.reportApiInvoke(null,{name:hT.GET_MEDIA_STREAM_TRACK,options:[],tag:pT.TRACER});this._mediaStreamTrack&&\"string\"==typeof this._mediaStreamTrack.label?e.onSuccess(this._mediaStreamTrack.label):e.onSuccess(\"\")}return this._mediaStreamTrack}getRTCRtpTransceiver(e){return e===GA.LOW_STREAM?this._lowRtpTransceiver:this._rtpTransceiver}getMediaStreamTrackSettings(){return this.getMediaStreamTrack(!0).getSettings()}close(){this._isClosed=!0,this._lowRtpTransceiver=void 0,this._rtpTransceiver=void 0,function(e){const t=VA.indexOf(e);-1!==t&&VA.splice(t,1)}(this),this.emit(YA.CLOSED),this.removeAllListeners(KA.SEI_RECEIVED)}_updateRtpTransceiver(e,t){if(t===GA.LOW_STREAM){if(this._lowRtpTransceiver===e)return;this._lowRtpTransceiver=e}else{if(this._rtpTransceiver===e)return;this._rtpTransceiver=e}this.emit(KA.TRANSCEIVER_UPDATED,e,t)}}class lb extends db{get isExternalTrack(){return this._isExternalTrack}get muted(){return this._muted}get enabled(){return this._enabled}get processorContext(){return this._processorContext}constructor(e,t){super(e,t),sh(this,\"_enabled\",!0),sh(this,\"_muted\",!1),sh(this,\"_isExternalTrack\",!1),sh(this,\"_isClosed\",!1),sh(this,\"_enabledMutex\",void 0),sh(this,\"processor\",void 0),sh(this,\"_handleTrackEnded\",(()=>{this.onTrackEnded()})),this._enabledMutex=new pS(\"\".concat(this.getTrackId())),e.addEventListener(\"ended\",this._handleTrackEnded)}getTrackLabel(){var e,t;return null!==(e=null===(t=this._originMediaStreamTrack)||void 0===t?void 0:t.label)&&void 0!==e?e:\"\"}close(){this._isClosed||(this.stop(),this._originMediaStreamTrack.stop(),this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack.stop(),this._mediaStreamTrack=null),this._originMediaStreamTrack=null,this._enabledMutex=null,jC.debug(\"[\".concat(this.getTrackId(),\"] close\")),this.emit(BA.NEED_CLOSE),super.close())}async _updateOriginMediaStreamTrack(e,t){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];this._isExternalTrack=i,e!==this._originMediaStreamTrack&&(this._originMediaStreamTrack&&(this._originMediaStreamTrack.removeEventListener(\"ended\",this._handleTrackEnded),t&&this._originMediaStreamTrack.stop()),e.addEventListener(\"ended\",this._handleTrackEnded),this._originMediaStreamTrack=e,this._muted&&(this._originMediaStreamTrack.enabled=!1),this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await yT(this,BA.NEED_REPLACE_TRACK,this),this.processor&&this._processorContext&&this.processor.updateInput({track:this._originMediaStreamTrack,context:this._processorContext}))}_getDefaultPlayerConfig(){return{}}onTrackEnded(){jC.debug(\"[\".concat(this.getTrackId(),\"] track ended\")),this.safeEmit(YA.TRACK_ENDED)}stateCheck(e,t){if(jC.debug(\"check track state, [muted: \".concat(this._muted,\", enabled: \").concat(this._enabled,\"] to [\").concat(e,\": \").concat(t,\"]\")),Yg(t,e),this._enabled&&this._muted&&\"enabled\"===e&&!1===t)throw new Kg(Hg.TRACK_STATE_UNREACHABLE,\"cannot set enabled while the track is muted\").print(\"error\",jC);if(!this._enabled&&!this._muted&&\"muted\"===e&&!0===t)throw new Kg(Hg.TRACK_STATE_UNREACHABLE,\"cannot set muted while the track is disabled\").print(\"error\",jC)}getProcessorStats(){return this._processorContext&&this._processorContext.gatherStats()||[]}getProcessorUsage(){return this._processorContext?this._processorContext.gatherUsage():cg.resolve([])}}function ub(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}const hb=window.AudioContext||window.webkitAudioContext;let pb=null;const _b=new class extends dT{constructor(){super(...arguments),sh(this,\"prevState\",void 0),sh(this,\"curState\",void 0),sh(this,\"currentTime\",void 0),sh(this,\"currentTimeStuckAt\",void 0),sh(this,\"interruptDetectorTrack\",void 0),sh(this,\"onLocalAudioTrackMute\",(()=>{jC.info(\"ios15-interruption-start\"),this.emit(vA.IOS_15_16_INTERRUPTION_START)})),sh(this,\"onLocalAudioTrackUnmute\",(async()=>{jC.info(\"ios15-interruption-end\"),\"running\"!==this.curState||this.duringInterruption?jC.info(\"ios15-interruption-end-canceled\"):(pb&&await pb.suspend(),this.emit(vA.IOS_15_16_INTERRUPTION_END))}))}get duringInterruption(){return\"running\"===this.prevState&&\"interrupted\"===this.curState}bindInterruptDetectorTrack(e){jC.debug(\"webaudio bindInterruptDetectorTrack \".concat(e.getTrackId())),this.interruptDetectorTrack||(this.interruptDetectorTrack=e,this.interruptDetectorTrack._mediaStreamTrack.onmute=this.onLocalAudioTrackMute,this.interruptDetectorTrack._mediaStreamTrack.onunmute=this.onLocalAudioTrackUnmute)}unbindInterruptDetectorTrack(e){jC.debug(\"webaudio unbindInterruptDetectorTrack \".concat(e.getTrackId())),this.interruptDetectorTrack&&this.interruptDetectorTrack===e&&(this.interruptDetectorTrack._mediaStreamTrack&&(this.interruptDetectorTrack._mediaStreamTrack.onmute=null,this.interruptDetectorTrack._mediaStreamTrack.onunmute=null),this.interruptDetectorTrack=void 0)}};function Eb(){if(!hb)return void jC.error(\"your browser is not support web audio\");jC.info(\"create audio context\");const e=function(e){for(var t=1;t{_b.prevState=_b.curState,_b.curState=pb?pb.state:void 0;const{prevState:e,curState:t}=_b,i=\"running\"===t,n=\"interrupted\"===t,r=\"running\"===e,s=\"suspended\"===e,o=\"interrupted\"===e,a=Sg().osVersion;(Og()||Vg())&&r&&n&&(jC.info(\"ios\".concat(a,\"-interruption-start\")),_b.emit(vA.IOS_INTERRUPTION_START)),(Og()||Vg())&&(s||o)&&i&&(jC.info(\"ios\".concat(a,\"-interruption-end\")),_b.emit(vA.IOS_INTERRUPTION_END)),e!==t&&_b.emit(vA.STATE_CHANGE,t,e)},setInterval((()=>{var e;const t=null===(e=pb)||void 0===e?void 0:e.currentTime;if(_b.currentTime!==t)_b.currentTimeStuckAt&&(jC.debug(\"AudioContext current time resume at \".concat(t)),_b.currentTimeStuckAt=void 0),_b.currentTime=t;else{if(t!==_b.currentTimeStuckAt){eI.reportApiInvoke(null,{name:\"WEB_AUDIO_CURRENT_TIME_STUCK\",options:{currentTime:t},tag:pT.TRACER}).onSuccess(),jC.warning(\"AudioContext current time stuck at \".concat(t))}_b.currentTimeStuckAt=t}}),5e3),async function(e){const t=[\"click\",\"contextmenu\",\"auxclick\",\"dblclick\",\"mousedown\",\"mouseup\",\"touchend\",\"keydown\",\"keyup\"];let i,n=!1,r=!1,s=!1;function o(t){\"running\"===e.state?a(!1):Og()||Vg()?\"suspended\"===e.state&&(a(!0),t&&e.resume().then(d,d)):\"closed\"!==e.state&&(a(!0),t&&e.resume().then(d,d))}function a(e){if(n!==e){n=e;for(let i=0,n=t;i\",i=n.children.item(0),i.controls=!1,i.disableRemotePlayback=!0,i.preload=\"auto\",i.srcObject=t.stream,u(!0)}_b.on(vA.STATE_CHANGE,c),o(!1)}(pb)}function mb(){if(!pb){if(Eb(),!pb)throw new Kg(Hg.NOT_SUPPORTED,\"can not create audio context\");return pb}return pb}function fb(e){if(function(){if(null!==gb)return gb;const e=mb(),t=e.createBufferSource(),i=e.createGain(),n=e.createGain();t.connect(i),t.connect(n),t.disconnect(i);let r=!1;try{t.disconnect(i)}catch(e){r=!0}return t.disconnect(),gb=r,r}())return;const t=e.connect,i=e.disconnect;e.connect=(i,n,r)=>{var s;return e._inputNodes||(e._inputNodes=[]),bn(s=e._inputNodes).call(s,i)||(i instanceof AudioNode?(e._inputNodes.push(i),t.call(e,i,n,r)):t.call(e,i,n)),e},e.disconnect=(n,r,s)=>{i.call(e),n?WT(e._inputNodes,n):e._inputNodes=[];for(const i of e._inputNodes)t.call(e,i)}}let gb=null;function Tb(e,t){let i=!1;const n=1/t;if(RC(\"DISABLE_WEBAUDIO\")){const t=window.setInterval((()=>{i?window.clearInterval(t):e(performance.now()/1e3)}),1e3*n)}else{const t=mb();let r=t.createGain();r.gain.value=0,r.connect(t.destination);const s=()=>{if(i)return void(r=null);const o=t.createOscillator();o.onended=s,o.connect(r),o.start(0),o.stop(t.currentTime+n),e(t.currentTime)};s()}return()=>{i=!0}}class Sb{constructor(){sh(this,\"context\",void 0),sh(this,\"analyserNode\",void 0),sh(this,\"sourceNode\",void 0),this.context=mb(),this.analyserNode=this.context.createAnalyser(),this.analyserNode.fftSize=2048,this.analyserNode.smoothingTimeConstant=.4}updateSource(e){if(e!==this.sourceNode){if(this.sourceNode)try{this.sourceNode.disconnect(this.analyserNode)}catch(e){}this.sourceNode=e,null==e||e.connect(this.analyserNode)}}getVolumeLevel(){if(!this.sourceNode)return 0;if(!this.context||Og()||Vg()||\"running\"!==this.context.state&&this.context.resume(),!this.analyserNode)return 0;const e=new Float32Array(this.analyserNode.fftSize);if(this.analyserNode.getFloatTimeDomainData)this.analyserNode.getFloatTimeDomainData(e);else{const t=new Uint8Array(this.analyserNode.fftSize);this.analyserNode.getByteTimeDomainData(t);for(let i=0;ie+t*t),0)/e.length;return Math.max(10*Math.log10(t)+100,0)/100}getAnalyserNode(){return this.analyserNode}rebuildAnalyser(){try{var e,t;null===(e=this.sourceNode)||void 0===e||e.disconnect(this.analyserNode),this.analyserNode=this.context.createAnalyser(),this.analyserNode.fftSize=2048,this.analyserNode.smoothingTimeConstant=.4,null===(t=this.sourceNode)||void 0===t||t.connect(this.analyserNode)}catch(e){jC.warning(\"rebuild analyser node failed.\")}}destroy(){this.updateSource(void 0)}}class Rb extends dT{get processSourceNode(){return this.sourceNode}set processedNode(e){var t;if(!this.isDestroyed&&this._processedNode!==e){try{var i;null===(i=this.sourceNode)||void 0===i||i.disconnect(this.outputNode)}catch(e){}null===(t=this._processedNode)||void 0===t||t.disconnect(),this._processedNode=e,this.connect()}}get processedNode(){return this._processedNode}constructor(){super(),sh(this,\"outputNode\",void 0),sh(this,\"outputTrack\",void 0),sh(this,\"isPlayed\",!1),sh(this,\"context\",void 0),sh(this,\"audioBufferNode\",void 0),sh(this,\"destNode\",void 0),sh(this,\"audioOutputLevel\",0),sh(this,\"volumeLevelAnalyser\",void 0),sh(this,\"_processedNode\",void 0),sh(this,\"playNode\",void 0),sh(this,\"isDestroyed\",!1),sh(this,\"onNoAudioInput\",void 0),sh(this,\"isNoAudioInput\",!1),sh(this,\"_noAudioInputCount\",0),this.context=mb(),this.playNode=this.context.destination,this.outputNode=this.context.createGain(),fb(this.outputNode),this.volumeLevelAnalyser=new Sb}startGetAudioBuffer(e){this.audioBufferNode||(this.audioBufferNode=this.context.createScriptProcessor(e),this.outputNode.connect(this.audioBufferNode),this.audioBufferNode.connect(this.context.destination),this.audioBufferNode.onaudioprocess=e=>{this.emit(zA.ON_AUDIO_BUFFER,function(e){for(let t=0;t{_b.emit(\"autoplay-failed\")})),this.isPlayed=!0,this.playNode=e||this.context.destination,this.outputNode.connect(this.playNode)}stop(){if(this.isPlayed)try{this.outputNode.disconnect(this.playNode)}catch(e){}this.isPlayed=!1}getAccurateVolumeLevel(){return this.volumeLevelAnalyser.getVolumeLevel()}async checkHasAudioInput(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;if(e>5)return this.isNoAudioInput=!0,this.onNoAudioInput&&this.onNoAudioInput(),!1;Og()||Vg()?\"suspended\"===this.context.state&&this.context.resume():\"running\"!==this.context.state&&this.context.resume();const t=this.volumeLevelAnalyser.getAnalyserNode();let i;t.getFloatTimeDomainData?(i=new Float32Array(t.fftSize),t.getFloatTimeDomainData(i)):(i=new Uint8Array(t.fftSize),t.getByteTimeDomainData(i));let n=!1;for(let e=0;e{if(jC.debug(\"ready to rebuild web audio, state:\",this.context.state),this.isNoAudioInput&&await this.checkHasAudioInput(),!this.isNoAudioInput||this.isDestroyed)return document.body.removeEventListener(\"click\",this.rebuildWebAudio,!0),void jC.debug(\"rebuild web audio success, current volume status\",this.getAccurateVolumeLevel());this.context.resume().then((()=>jC.info(\"resume success\"))),jC.debug(\"rebuild web audio because of ios 12 bugs\"),this.disconnect();const e=this.track;this.track=this.track.clone(),this.isCurrentTrackCloned?e.stop():this.isCurrentTrackCloned=!0;const t=new MediaStream([this.track]);this.sourceNode=this.context.createMediaStreamSource(t),fb(this.sourceNode),this.volumeLevelAnalyser.rebuildAnalyser();const i=this.outputNode.gain.value;this.outputNode=this.context.createGain(),this.outputNode.gain.setValueAtTime(i,this.context.currentTime),fb(this.outputNode),this.emit(zA.UPDATE_SOURCE),this.connect(),this.audioElement.srcObject=t,this.isPlayed&&this.play(this.playNode),this.checkHasAudioInput()})),\"audio\"!==e.kind)throw new Kg(Hg.UNEXPECTED_ERROR);this.track=e;const r=new MediaStream([this.track]);if(this.isRemoteTrack=!!t,this.sourceNode=this.context.createMediaStreamSource(r),fb(this.sourceNode),i){const e=i.clone();e.enabled=!0,this.clonedTrack=e,jC.debug(\"create an unmuted track \".concat(e.id,\" from the original track \").concat(i.id,\" to get the volume\"));const t=this.context.createMediaStreamSource(new MediaStream([e]));fb(t),this.originVolumeLevelAnalyser=new Sb,this.originVolumeLevelAnalyser.updateSource(t)}this.connect(),this.audioElement=document.createElement(\"audio\"),this.audioElement.srcObject=r;const s=Sg();t&&s.os===_g.IOS&&Number(null===(n=s.osVersion)||void 0===n?void 0:n.split(\".\")[0])<15&&(_b.on(vA.STATE_CHANGE,(()=>{\"suspended\"===this.context.state?document.body.addEventListener(\"click\",this.rebuildWebAudio,!0):\"running\"===this.context.state&&this.rebuildWebAudio()})),this.checkHasAudioInput().then((e=>{e||document.body.addEventListener(\"click\",this.rebuildWebAudio,!0)})))}updateTrack(e){this.sourceNode.disconnect(),this.track=e,this.isCurrentTrackCloned=!1;const t=new MediaStream([e]);this.sourceNode=this.context.createMediaStreamSource(t),fb(this.sourceNode),this.processedNode||this.sourceNode.connect(this.outputNode),this.emit(zA.UPDATE_SOURCE),this.audioElement.srcObject=t}destroy(){var e;this.audioElement.srcObject=null,this.audioElement.remove(),_b.off(\"state-change\",this.rebuildWebAudio),null===(e=this.originVolumeLevelAnalyser)||void 0===e||e.destroy(),this.clonedTrack=void 0,super.destroy()}createMediaStreamSourceNode(e){return this.context.createMediaStreamSource(new MediaStream([e]))}updateOriginTrack(e){const t=e.clone();t.enabled=!0,this.clonedTrack&&(this.clonedTrack.stop(),this.clonedTrack=t),jC.debug(\"create an unmuted track \".concat(t.id,\" from the original track \").concat(e.id,\" to get the volume\"));const i=this.context.createMediaStreamSource(new MediaStream([t]));fb(i),this.originVolumeLevelAnalyser&&this.originVolumeLevelAnalyser.updateSource(i)}getOriginVolumeLevel(){return this.originVolumeLevelAnalyser?this.originVolumeLevelAnalyser.getVolumeLevel():this.getAccurateVolumeLevel()}}async function Ib(e,t,i){const n=(e,t)=>e?\"number\"!=typeof e?e.max||e.exact||e.ideal||e.min||t:e:t,r={audio:!!i&&{mandatory:{chromeMediaSource:\"desktop\"}},video:{mandatory:{chromeMediaSource:\"desktop\",chromeMediaSourceId:e,maxHeight:n(t.height,1080),maxWidth:n(t.width,1920)}}};return t.frameRate&&\"number\"!=typeof t.frameRate?(r.video.mandatory.maxFrameRate=t.frameRate.max,r.video.mandatory.minFrameRate=t.frameRate.min):\"number\"==typeof t.frameRate&&(r.video.mandatory.maxFrameRate=t.frameRate),await navigator.mediaDevices.getUserMedia(r)}async function vb(e,t){const i=await yb(e.mediaSource),{sourceId:n,audio:r}=await function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return new cg(((i,n)=>{const r=document.createElement(\"div\");r.innerText=\"share screen\",r.setAttribute(\"style\",\"text-align: center; height: 25px; line-height: 25px; border-radius: 4px 4px 0 0; background: #D4D2D4; border-bottom: solid 1px #B9B8B9;\");const s=document.createElement(\"div\");s.setAttribute(\"style\",\"width: 100%; height: 500px; padding: 15px 25px ; box-sizing: border-box;\");const o=document.createElement(\"div\");o.innerText=\"Agora Web Screensharing wants to share the contents of your screen with webdemo.agorabeckon.com. Choose what you'd like to share.\",o.setAttribute(\"style\",\"height: 12%;\");const a=document.createElement(\"div\");a.setAttribute(\"style\",\"width: 100%; height: 80%; background: #FFF; border: solid 1px #CBCBCB; display: flex; flex-wrap: wrap; justify-content: space-around; overflow-y: scroll; padding: 0 15px; box-sizing: border-box;\");const c=document.createElement(\"div\");c.setAttribute(\"style\",\"display: flex; justify-content: space-between; padding: 16px 0;\");const d=document.createElement(\"button\");d.innerHTML=\"cancel\",d.setAttribute(\"style\",\"width: 85px;\"),d.onclick=()=>{document.body.removeChild(h);const e=new Error(\"NotAllowedError\");e.name=\"NotAllowedError\",n(e)};let l=t;const u=document.createElement(\"div\");if(t){const e=document.createElement(\"input\");e.setAttribute(\"type\",\"checkbox\");const t=document.createElement(\"span\");e.setAttribute(\"style\",\"margin-right: 6px;\"),t.innerText=\"Share audio\",e.checked=l,e.onchange=()=>{l=e.checked},u.appendChild(e),u.appendChild(t)}c.appendChild(u),c.appendChild(d),s.appendChild(o),s.appendChild(a),s.appendChild(c);const h=document.createElement(\"div\");h.setAttribute(\"style\",\"position: fixed; z-index: 99999999; top: 50%; left: 50%; width: 620px; height: 525px; background: #ECECEC; border-radius: 4px; -webkit-transform: translate(-50%,-50%); transform: translate(-50%,-50%);\"),h.appendChild(r),h.appendChild(s),document.body.appendChild(h),e.map((e=>{if(e.id){const t=document.createElement(\"div\");t.setAttribute(\"style\",\"width: 30%; height: 160px; padding: 20px 0; text-align: center;box-sizing: content-box;\");let n=e.thumbnail;try{const{width:e}=n.getSize();e>1920&&(n=n.resize({width:1920}))}catch(e){throw e&&e.message.startsWith(\"Illegal invocation\")&&console.error(\"Operate thumbnail error, please try to set contextIsolation: false. (https://github.com/electron/electron/issues/34953)\"),e}t.innerHTML='
'+e.name.replace(/[\\u00A0-\\u9999<>\\&]/g,(function(e){return\"&#\"+e.charCodeAt(0)+\";\"}))+\"\",t.onclick=()=>{document.body.removeChild(h),i({sourceId:e.id,audio:l})},a.appendChild(t)}}))}))}(i,t);return await Ib(n,e,r)}async function yb(e){let t=[\"window\",\"screen\"];\"application\"!==e&&\"window\"!==e||(t=[\"window\"]),\"screen\"===e&&(t=[\"screen\"]);const i=uT();if(!i)throw console.error(\"failed to fetch electron, please mount it to window\"),new Kg(Hg.ELECTRON_IS_NULL);let n=null;try{var r;n=(null===(r=i.desktopCapturer)||void 0===r?void 0:r.getSources({types:t}))||i.ipcRenderer.invoke(\"DESKTOP_CAPTURER_GET_SOURCES\",{types:t})}catch(e){n=null}n&&n.then||(n=new cg(((e,n)=>{i.desktopCapturer.getSources({types:t},((t,i)=>{t?n(t):e(i)}))})));try{return await n}catch(e){throw new Kg(Hg.ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR,e.toString())}}function Ab(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}const bb=new pS(\"safari\");let wb=!1,Ob=!1;async function Nb(e,t){let i=0,n=null;for(;i<2;)try{n=await Db(e,t,i>0);break}catch(e){if(e instanceof Kg)throw jC.error(\"[\".concat(t,\"] \").concat(e.toString())),e;const n=Pb(e.name||e.code||e,e.message);if(n.code===Hg.MEDIA_OPTION_INVALID){jC.debug(\"[\".concat(t,\"] detect media option invalid, retry\")),i+=1,await iS(500);continue}throw jC.error(\"[\".concat(t,\"] \").concat(n.toString())),n}if(!n)throw new Kg(Hg.UNEXPECTED_ERROR,\"can not find stream after getUserMedia\");return n}async function Db(e,t,i){if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)throw new Kg(Hg.NOT_SUPPORTED,\"can not find getUserMedia\");i&&(e.video&&(delete e.video.width,delete e.video.height),e.screen&&(delete e.screen.width,delete e.screen.height));const n=IA(),r=new MediaStream;if(e.audioSource&&r.addTrack(e.audioSource),e.videoSource&&r.addTrack(e.videoSource),!e.audio&&!e.video&&!e.screen)return jC.debug(\"Using Video Source/ Audio Source\"),r;if(e.screen)if(uT())if(e.screen.sourceId){Lb(r,await Ib(e.screen.sourceId,e.screen,e.screenAudio))}else{Lb(r,await vb(e.screen,e.screenAudio))}else if(Ag()&&e.screen.extensionId&&e.screen.mandatory){if(!n.getStreamFromExtension)throw new Kg(Hg.NOT_SUPPORTED,\"This browser does not support screen sharing\");jC.debug(\"[\".concat(t,'] Screen access on chrome stable, looking for extension\"'));const i=await(o=e.screen.extensionId,a=t,new cg(((e,t)=>{try{chrome.runtime.sendMessage(o,{getStream:!0},(i=>{if(!i||!i.streamId)return jC.error(\"[\".concat(a,\"] No response from Chrome Plugin. Plugin not installed properly\"),i),void t(new Kg(Hg.CHROME_PLUGIN_NO_RESPONSE,\"No response from Chrome Plugin. Plugin not installed properly\"));e(i.streamId)}))}catch(e){jC.error(\"[\".concat(a,\"] AgoraRTC screensharing plugin is not accessible(\").concat(o,\")\"),e.toString()),t(new Kg(Hg.CHROME_PLUGIN_NOT_INSTALL))}})));e.screen.mandatory.chromeMediaSourceId=i;Lb(r,await navigator.mediaDevices.getUserMedia({video:{mandatory:e.screen.mandatory}}))}else if(n.getDisplayMedia){var s;e.screen.mediaSource&&FA(e.screen.mediaSource);const i={width:e.screen.width,height:e.screen.height,frameRate:e.screen.frameRate,displaySurface:null!==(s=e.screen.displaySurface)&&void 0!==s?s:\"screen\"===e.screen.mediaSource?\"monitor\":e.screen.mediaSource},{selfBrowserSurface:n,surfaceSwitching:o,systemAudio:a}=e.screen,c={selfBrowserSurface:n,surfaceSwitching:o,systemAudio:a};!n&&delete c.selfBrowserSurface,!o&&delete c.surfaceSwitching,!a&&delete c.systemAudio,jC.debug(\"[\".concat(t,\"] getDisplayMedia:\"),JSON.stringify({video:i,audio:!!e.screenAudio,controls:c}));const d=await navigator.mediaDevices.getDisplayMedia(function(e){for(var t=1;t{navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener(\"devicechange\",this.updateDevicesInfo.bind(this)),window.setInterval((()=>{(RC(\"ENUMERATE_DEVICES_INTERVAL\")||(Gg()||Rg()===_g.HARMONY_OS)&&jg())&&this.updateDevicesInfo()}),RC(\"ENUMERATE_DEVICES_INTERVAL_TIME\"))})).catch((e=>jC.error(e.toString())))}async enumerateDevices(e,t){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices){return new Kg(Hg.NOT_SUPPORTED,\"enumerateDevices() not supported.\").throw()}const n=await navigator.mediaDevices.enumerateDevices(),r=this.checkMediaDeviceInfoIsOk(n);let s=!this.isAccessMicrophonePermission&&e,o=!this.isAccessCameraPermission&&t;r.audio&&(s=!1),r.video&&(o=!1);let a=null,c=null,d=null;if(!i&&(s||o)){if(bb.isLocked){jC.debug(\"[device manager] wait GUM lock\");(await bb.lock())(),jC.debug(\"[device manager] GUM unlock\")}if(wb&&(s=!1,this.isAccessMicrophonePermission=!0),Ob&&(o=!1,this.isAccessCameraPermission=!0),jC.debug(\"[device manager] check media device permissions\",e,t,s,o),s&&o){try{d=await navigator.mediaDevices.getUserMedia({audio:!0,video:!0})}catch(e){const t=Pb(e.name||e.code||e,e.message);if(t.code===Hg.PERMISSION_DENIED)throw t;jC.warning(\"getUserMedia failed in getDevices\",t)}this.isAccessCameraPermission=!0,this.isAccessMicrophonePermission=!0}else if(s){try{a=await navigator.mediaDevices.getUserMedia({audio:e})}catch(e){const t=Pb(e.name||e.code||e,e.message);if(t.code===Hg.PERMISSION_DENIED)throw t;jC.warning(\"getUserMedia failed in getDevices\",t)}this.isAccessMicrophonePermission=!0}else if(o){try{c=await navigator.mediaDevices.getUserMedia({video:t})}catch(e){const t=Pb(e.name||e.code||e,e.message);if(t.code===Hg.PERMISSION_DENIED)throw t;jC.warning(\"getUserMedia failed in getDevices\",t)}this.isAccessCameraPermission=!0}jC.debug(\"[device manager] mic permission\",e,\"cam permission\",t)}try{const e=await navigator.mediaDevices.enumerateDevices();return a&&a.getTracks().forEach((e=>e.stop())),c&&c.getTracks().forEach((e=>e.stop())),d&&d.getTracks().forEach((e=>e.stop())),a=null,c=null,d=null,e}catch(e){a&&a.getTracks().forEach((e=>e.stop())),c&&c.getTracks().forEach((e=>e.stop())),d&&d.getTracks().forEach((e=>e.stop())),a=null,c=null,d=null;return new Kg(Hg.ENUMERATE_DEVICES_FAILED,e.toString()).throw()}}async getRecordingDevices(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return(await this.enumerateDevices(!0,!1,e)).filter((e=>\"audioinput\"===e.kind))}async getCamerasDevices(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return(await this.enumerateDevices(!1,!0,e)).filter((e=>\"videoinput\"===e.kind))}async getSpeakers(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return(await this.enumerateDevices(!0,!1,e)).filter((e=>\"audiooutput\"===e.kind))}searchDeviceIdByName(e){let t=null;return this.deviceInfoMap.forEach((i=>{i.device.label===e&&(t=i.device.deviceId)})),t}async getDeviceById(e){const t=(await this.enumerateDevices(!0,!0,!0)).find((t=>t.deviceId===e));if(!t)throw new Kg(Hg.DEVICE_NOT_FOUND,\"deviceId: \".concat(e));return t}async init(){this.state=nb.INITING;try{await this.updateDevicesInfo(),this.state=nb.INITEND}catch(e){if(jC.warning(\"Device Detection functionality cannot start properly.\",e.toString()),this.state=nb.IDLE,!(\"boolean\"==typeof isSecureContext?isSecureContext:\"https:\"===location.protocol||\"file:\"===location.protocol||\"localhost\"===location.hostname||\"127.0.0.1\"===location.hostname||\"::1\"===location.hostname)){new Kg(Hg.WEB_SECURITY_RESTRICT,\"Your context is limited by web security, please try using https protocol or localhost.\").throw()}throw e}}async updateDevicesInfo(){const e=await this.enumerateDevices(!0,!0,!0),t=Date.now(),i=[];if(e[0]&&e[0].label&&!1===this.checkdeviceMatched){this.checkdeviceMatched=!0;const t=e.find((e=>\"audioinput\"===e.kind&&\"default\"===e.deviceId)),i=e.find((e=>\"audiooutput\"===e.kind&&\"default\"===e.deviceId));t&&i?i.groupId===t.groupId?jC.debug(\"[device-check] default input \".concat(t.label,\" and output \").concat(i.label,\" is the same group\")):jC.warning(\"[device-check] default input \".concat(t.label,\" and output \").concat(i.label,\" is not the same group\")):jC.debug(\"[device-check] default input or output not found\")}const n=this.checkMediaDeviceInfoIsOk(e);if(e.forEach((e=>{if(!e.deviceId)return;const n=this.deviceInfoMap.get(\"\".concat(e.kind,\"_\").concat(e.deviceId));if(\"ACTIVE\"!==(n?n.state:\"INACTIVE\")){const n={initAt:t,updateAt:t,device:e,state:\"ACTIVE\"};this.deviceInfoMap.set(\"\".concat(e.kind,\"_\").concat(e.deviceId),n),i.push(n)}n&&(n.updateAt=t)})),this.deviceInfoMap.forEach(((e,n)=>{\"ACTIVE\"===e.state&&e.updateAt!==t&&(e.state=\"INACTIVE\",i.push(e))})),this.state!==nb.INITEND)return n.audio&&(this.lastAccessMicrophonePermission=!0,this.isAccessMicrophonePermission=!0),void(n.video&&(this.lastAccessCameraPermission=!0,this.isAccessCameraPermission=!0));i.forEach((e=>{switch(e.device.kind){case\"audioinput\":this.lastAccessMicrophonePermission&&this.isAccessMicrophonePermission&&this.emit(rb.RECORDING_DEVICE_CHANGED,e);break;case\"videoinput\":this.lastAccessCameraPermission&&this.isAccessCameraPermission&&this.emit(rb.CAMERA_DEVICE_CHANGED,e);break;case\"audiooutput\":this.lastAccessMicrophonePermission&&this.isAccessMicrophonePermission&&this.emit(rb.PLAYOUT_DEVICE_CHANGED,e)}})),n.audio&&(this.lastAccessMicrophonePermission=!0,this.isAccessMicrophonePermission=!0),n.video&&(this.lastAccessCameraPermission=!0,this.isAccessCameraPermission=!0)}checkMediaDeviceInfoIsOk(e){const t=e.filter((e=>\"audioinput\"===e.kind)),i=e.filter((e=>\"videoinput\"===e.kind)),n={audio:!1,video:!1};for(const e of t)if(e.label&&e.deviceId){n.audio=!0;break}for(const e of i)if(e.label&&e.deviceId){n.video=!0;break}return n}};let Mb=!1;const Ub=new class extends dT{constructor(){super(...arguments),sh(this,\"onAutoplayFailed\",void 0),sh(this,\"onAudioAutoplayFailed\",void 0)}};function xb(){if(Sg(),!Mb){const e=t=>{t.preventDefault(),Mb=!1,Wg()?document.body.removeEventListener(\"click\",e,!0):(document.body.removeEventListener(\"touchstart\",e,!0),document.body.removeEventListener(\"mousedown\",e,!0))};Mb=!0,Wg()?document.body.addEventListener(\"click\",e,!0):(document.body.addEventListener(\"touchstart\",e,!0),document.body.addEventListener(\"mousedown\",e,!0)),jC.info(\"detect media autoplay failed, document: https://docs.agora.io/cn/Voice/autoplay_policy_web_ng?platform=Web\"),Ub.onAutoplayFailed?Ub.onAutoplayFailed():Ub.onAudioAutoplayFailed?jC.warning(\"AgoraRTC.onAudioAutoplayFailed has been deprecated in favor of AgoraRTC.onAutoplayFailed.\\n\\n Please refer to the Agora document to migrate the newer API, https://docs.agora.io/en/Voice/autoplay_policy_web_ng?platform=Web .\"):jC.warning(\"We have detected a media autoplay failed event, and found out that you haven't implemented AgoraRTC.onAutoplayFailed callback yet.\\n\\n It will cause audio/video element not playing automatically on some browsers without user interaction, possibly hurting user experiences.\\n\\n Please refer to the Agora document to properly handle autoplay failed event, https://docs.agora.io/en/Voice/autoplay_policy_web_ng?platform=Web .\"),Ub.emit(\"autoplay-failed\")}}function Vb(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function Fb(e){for(var t=1;t{Array.from(this.elementMap.entries()).forEach((t=>{let[i,n]=t;const r=this.elementStateMap.get(i),s=n.srcObject.getAudioTracks()[0],o=s&&s.readyState;if(jC.debug(\"resume after interrupted, ele: \".concat(r,\" audio: \").concat(o,\" \").concat(e)),\"live\"===o){if(e)return n.pause(),void n.play();if(\"running\"===_b.curState)return Mg()?(n.pause(),void n.play()):void(r&&\"paused\"===r&&n.play())}}))})),sh(this,\"autoResumeAfterInterruptionOnIOS15_16\",(()=>{Array.from(this.elementMap.entries()).forEach((e=>{let[t,i]=e;const n=i.srcObject.getAudioTracks()[0];n&&\"live\"===n.readyState&&(jC.debug(\"auto resume after interruption inside autoResumeAfterInterruptionOnIOS15\"),i.pause(),i.play())}))})),this.autoResumeAudioElement(),_b.on(vA.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),_b.on(vA.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16),_b.on(vA.STATE_CHANGE,(()=>{Og()&&\"suspended\"===_b.prevState&&\"running\"===_b.curState&&this.autoResumeAfterInterruption()}))}async setSinkID(e,t){const i=this.elementMap.get(e);if(this.sinkIdMap.set(e,t),i)try{await i.setSinkId(t)}catch(e){throw new Kg(Hg.PERMISSION_DENIED,\"can not set sink id: \"+e.toString())}}play(e,t,i,n){if(this.elementMap.has(t))return;const r=document.createElement(\"audio\");r.autoplay=!0,r.srcObject=new MediaStream([e]),this.bindAudioElementEvents(t,r),this.elementMap.set(t,r),this.elementStateMap.set(t,sb.INIT),this.setVolume(t,i);const s=this.sinkIdMap.get(t);if(s)try{r.setSinkId(s).catch((e=>{jC.warning(\"[\".concat(t,\"] set sink id failed\"),e.toString())}))}catch(e){jC.warning(\"[\".concat(t,\"] set sink id failed\"),e.toString())}const o=r.play();o&&o.then&&o.catch((e=>{n&&Bb(n,\"audio\",e.message,t),jC.warning(\"audio element play warning\",e.toString()),this.elementMap.has(t)&&\"NotAllowedError\"===e.name&&(jC.warning(\"detected audio element autoplay failed\"),this.elementsNeedToResume.push(r),KT((()=>{this.onAutoplayFailed&&this.onAutoplayFailed(),xb()})))}))}updateTrack(e,t){const i=this.elementMap.get(e);i&&(i.srcObject=new MediaStream([t]))}isPlaying(e){return this.elementMap.has(e)&&\"playing\"===this.elementStateMap.get(e)}setVolume(e,t){const i=this.elementMap.get(e);i&&(t=Math.max(0,Math.min(100,t)),i.volume=t/100)}stop(e){const t=this.elementMap.get(e);if(this.sinkIdMap.delete(e),!t)return;const i=this.elementsNeedToResume.indexOf(t);this.elementsNeedToResume.splice(i,1),t.srcObject=null,t.remove(),this.elementMap.delete(e),this.elementStateMap.delete(e)}bindAudioElementEvents(e,t){jb.forEach((i=>{t.addEventListener(i,(i=>{const n=this.elementStateMap.get(e),r=\"pause\"===i.type?\"paused\":i.type;if(jC.debug(\"[\".concat(e,\"] audio-element-status change \").concat(n,\" => \").concat(r)),\"error\"===i.type){const i=null==t?void 0:t.error;i&&jC.error(\"[\".concat(e,\"] media error, code: \").concat(i.code,\", message: \").concat(i.message))}this.elementStateMap.set(e,r)}))}))}getPlayerState(e){return this.elementStateMap.get(e)||\"uninit\"}autoResumeAudioElement(){const e=()=>{this.elementsNeedToResume.forEach((e=>{e.play().then((e=>{jC.debug(\"Auto resume audio element success\")})).catch((e=>{jC.warning(\"Auto resume audio element failed!\",e)}))})),this.elementsNeedToResume=[]};new cg((e=>{document.body?e():window.addEventListener(\"load\",(()=>e()))})).then((()=>{Wg()?document.body.addEventListener(\"click\",e,!0):(document.body.addEventListener(\"touchstart\",e,!0),document.body.addEventListener(\"mousedown\",e,!0))}))}};function Wb(){return function(e,t,i){const n=i.value;return\"function\"==typeof n&&(i.value=function(){this._isClosed&&new Kg(Hg.INVALID_OPERATION,\"[\".concat(this.getTrackId(),\"] cannot operate a closed track\")).print(\"warning\",jC);for(var e=arguments.length,t=new Array(e),i=0;i{r.then(e).catch(t)})):r}),i}}function Hb(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function Kb(e){for(var t=1;ti.processorID===e.ID&&i.processorName===e.name&&i.type===t))||this.statsRegistry.push({processorName:e.name,processorID:e.ID,type:t,cb:i})}unregisterStats(e,t){const i=this.statsRegistry.findIndex((i=>i.processorID===e.ID&&i.processorName===e.name&&i.type===t));-1!==i&&this.statsRegistry.splice(i,1)}gatherStats(){const e=[];for(const{processorID:t,processorName:i,type:n,cb:r}of this.statsRegistry)try{const s=r();e.push({processorID:t,processorName:i,type:n,stats:s})}catch(e){jC.error(new Kg(Hg.UNEXPECTED_ERROR,e.message))}return e}registerUsage(e,t){this.usageRegistry.find((t=>t.processorID===e.ID&&t.processorName===e.name))||this.usageRegistry.push({processorID:e.ID,processorName:e.name,cb:t})}unregisterUsage(e){const t=this.usageRegistry.findIndex((t=>t.processorID===e.ID&&t.processorName===e.name));-1!==t&&this.usageRegistry.splice(t,1)}async gatherUsage(){const e=[];if(!this.chained)return[];for(const{cb:t}of this.usageRegistry)try{let i=t();i instanceof cg&&(i=await i),e.push(Kb(Kb({},i),{},{direction:this.direction}))}catch(e){jC.error(\"gather extension usage error\",e)}return e}getDirection(){return this.direction}}class zb extends dT{constructor(e){super(),sh(this,\"name\",\"AudioProcessorDestination\"),sh(this,\"ID\",\"0\"),sh(this,\"inputTrack\",void 0),sh(this,\"inputNode\",void 0),sh(this,\"audioProcessorContext\",void 0),sh(this,\"_source\",void 0),this.audioProcessorContext=e}get kind(){return\"audio\"}get enabled(){return!0}pipe(){throw new Kg(Hg.NOT_SUPPORTED,\"AudioProcessorDestination cannot pipe to any other Processor\")}unpipe(){throw new Kg(Hg.NOT_SUPPORTED,\"AudioProcessor cannot unpipe to any other Processor\")}enable(){}disable(){}reset(){this.inputTrack=void 0,this.inputNode=void 0,this.audioProcessorContext.chained=!1,this.emit(tb.ON_TRACK,void 0),this.emit(tb.ON_NODE,void 0)}updateInput(e){if(e.context!==this.audioProcessorContext)throw new Error(\"ProcessorContext passed to AudioTrack.processorDestination doesn't match it's belonging AudioTrack's context.\\n Probably you are making pipeline like this: audioTrack1.pipe(processor).pipe(audioTrack2.processorDestination).\");e.track&&this.inputTrack!==e.track&&(this.audioProcessorContext.chained=!0,this.inputTrack=e.track,this.emit(tb.ON_TRACK,this.inputTrack)),e.node&&this.inputNode!==e.node&&(this.audioProcessorContext.chained=!0,this.inputNode=e.node,this.emit(tb.ON_NODE,this.inputNode))}}class Jb extends dT{set chained(e){this._chained=e}get chained(){return this._chained}constructor(e,t,i){super(),sh(this,\"constraintsMap\",new Map),sh(this,\"statsRegistry\",[]),sh(this,\"audioContext\",void 0),sh(this,\"trackId\",void 0),sh(this,\"direction\",void 0),sh(this,\"usageRegistry\",[]),sh(this,\"_chained\",!1),this.audioContext=e,this.trackId=t,this.direction=i}async getConstraints(){return vT(this,ib.REQUEST_CONSTRAINTS)}getAudioContext(){return this.audioContext}async requestApplyConstraints(e,t){var i;return jC.info(\"processor \".concat(t.name,\" requestApplyConstraints for \").concat(this.trackId)),e&&this.constraintsMap.set(t,e),yT(this,ib.REQUEST_UPDATE_CONSTRAINTS,Array.from(NI(i=this.constraintsMap).call(i)))}async requestRevertConstraints(e){var t;if(this.constraintsMap.has(e))return this.constraintsMap.delete(e),yT(this,ib.REQUEST_UPDATE_CONSTRAINTS,Array.from(NI(t=this.constraintsMap).call(t)))}registerStats(e,t,i){this.statsRegistry.find((i=>i.processorID===e.ID&&i.processorName===e.name&&i.type===t))||this.statsRegistry.push({processorName:e.name,processorID:e.ID,type:t,cb:i})}unregisterStats(e,t){const i=this.statsRegistry.findIndex((i=>i.processorID===e.ID&&i.processorName===e.name&&i.type===t));-1!==i&&this.statsRegistry.splice(i,1)}gatherStats(){const e=[];for(const{processorID:t,processorName:i,type:n,cb:r}of this.statsRegistry)try{const s=r();e.push({processorID:t,processorName:i,type:n,stats:s})}catch(e){jC.error(new Kg(Hg.UNEXPECTED_ERROR,e.message))}return e}registerUsage(e,t){this.usageRegistry.find((t=>t.processorID===e.ID&&t.processorName===e.name))||this.usageRegistry.push({processorID:e.ID,processorName:e.name,cb:t})}unregisterUsage(e){const t=this.usageRegistry.findIndex((t=>t.processorID===e.ID&&t.processorName===e.name));-1!==t&&this.usageRegistry.splice(t,1)}async gatherUsage(){const e=[];if(!this.chained)return[];for(const{cb:t}of this.usageRegistry)try{let i=t();i instanceof cg&&(i=await i),e.push(Kb(Kb({},i),{},{direction:this.direction}))}catch(e){jC.error(\"gather extension usage error\",e)}return e}getDirection(){return this.direction}}class Xb extends dT{get isPlayed(){return!0}get isFreeze(){return!1}constructor(){super(),sh(this,\"context\",void 0),sh(this,\"processSourceNode\",void 0),sh(this,\"outputTrack\",void 0),sh(this,\"processedNode\",void 0),sh(this,\"clonedTrack\",void 0),sh(this,\"outputNode\",void 0),this.outputNode=new Qb}setVolume(){}createOutputTrack(){throw new Kg(Hg.NOT_SUPPORTED,\"can not create output MediaStreamTrack when WebAudio disabled\")}getOriginVolumeLevel(){return 0}getAccurateVolumeLevel(){return 0}stopGetAudioBuffer(){}startGetAudioBuffer(){}play(){}stop(){}destroy(){}updateTrack(){}updateOriginTrack(){}createMediaStreamSourceNode(){}}class Qb{disconnect(){}connect(){}}function Zb(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function $b(e){for(var t=1;tthis.initWebAudio())):this.initWebAudio()}setVolume(e){zg(e,\"volume\",0,1e3),this._volume=e,this._source.setVolume(e/100),this._useAudioElement&&Gb.setVolume(this.getTrackId(),e);try{if(this._bypassWebAudio)return void jC.debug(\"[\".concat(this.getTrackId(),\"] setVolume returned because no pass through WebAudio.\"));const e=this._source.createOutputTrack();this._mediaStreamTrack!==e&&(this._mediaStreamTrack=e,yT(this,BA.NEED_REPLACE_TRACK,this).then((()=>{jC.debug(\"[\".concat(this.getTrackId(),\"] replace web audio track success\"))})).catch((e=>{jC.warning(\"[\".concat(this.getTrackId(),\"] replace web audio track failed\"),e)})))}catch(e){}}getVolumeLevel(){return this._muted&&this.enabled&&this._getOriginVolumeLevel?this._source.getOriginVolumeLevel():this._source.getAccurateVolumeLevel()}async setPlaybackDevice(e){if(!this._useAudioElement||!Ag()&&RC(\"RESTRICTION_SET_PLAYBACK_DEVICE\"))throw new Kg(Hg.NOT_SUPPORTED,\"your browser does not support setting the audio output device\");await Gb.setSinkID(this.getTrackId(),e)}async setEnabled(e,t,i){return this._setEnabled(e,t,i)}async _setEnabled(e,t,i){if(!i){if(e===this._enabled)return;this.stateCheck(\"enabled\",e)}if(jC.info(\"[\".concat(this.getTrackId(),\"] start setEnabled\"),e),e){this._originMediaStreamTrack.enabled=!0;try{i||(this._enabled=!0),await yT(this,BA.NEED_ENABLE_TRACK,this),jC.info(\"[\".concat(this.getTrackId(),\"] setEnabled to \").concat(e,\" success\"))}catch(e){throw i||(this._enabled=!1),jC.error(\"[\".concat(this.getTrackId(),\"] setEnabled to true error\"),e.toString()),e}}else{this._originMediaStreamTrack.enabled=!1,i||(this._enabled=!1);try{await yT(this,BA.NEED_DISABLE_TRACK,this)}catch(e){throw i||(this._enabled=!0),jC.error(\"[\".concat(this.getTrackId(),\"] setEnabled to false error\"),e.toString()),e}}}async setMuted(e){e!==this._muted&&(this.stateCheck(\"muted\",e),this._muted=e,this._originMediaStreamTrack.enabled=!e,jC.debug(\"[\".concat(this.getTrackId(),\"] start set muted: \").concat(e)),e?await yT(this,BA.NEED_MUTE_TRACK,this):await yT(this,BA.NEED_UNMUTE_TRACK,this))}getStats(){JT((()=>{jC.warning(\"[deprecated] LocalAudioTrack.getStats will be removed in the future, use AgoraRTCClient.getLocalAudioStats instead\")}),\"localAudioTrackGetStatsWarning\");const e=AT(this,BA.GET_STATS);return e||$b({},XA)}setAudioFrameCallback(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:4096;if(!e)return this._source.removeAllListeners(zA.ON_AUDIO_BUFFER),void this._source.stopGetAudioBuffer();this._source.startGetAudioBuffer(t),this._source.removeAllListeners(zA.ON_AUDIO_BUFFER),this._source.on(zA.ON_AUDIO_BUFFER,(t=>e(t)))}play(){jC.debug(\"[\".concat(this.getTrackId(),\"] start audio playback\")),this._useAudioElement?(jC.debug(\"[\".concat(this.getTrackId(),\"] start audio playback in element\")),Gb.play(this._mediaStreamTrack,this.getTrackId(),this._volume)):this._source.play()}stop(){jC.debug(\"[\".concat(this.getTrackId(),\"] stop audio playback\")),this._useAudioElement?Gb.stop(this.getTrackId()):this._source.stop()}close(){super.close(),this._processorDestination&&this.unbindProcessorDestinationEvents(this._processorDestination),this._processorContext&&this.unbindProcessorContextEvents(this._processorContext),this.unpipe(),this._processorDestination&&this._processorDestination._source&&this._processorDestination._source.unpipe(),this._source.destroy()}_updatePlayerSource(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];jC.debug(\"[\".concat(this.getTrackId(),\"] update player source track\")),e&&this._source.updateTrack(this._mediaStreamTrack),this._useAudioElement&&Gb.updateTrack(this.getTrackId(),this._mediaStreamTrack)}async _updateOriginMediaStreamTrack(e,t){this._originMediaStreamTrack!==e&&(this._originMediaStreamTrack&&(this._originMediaStreamTrack.removeEventListener(\"ended\",this._handleTrackEnded),t&&this._originMediaStreamTrack.stop()),e.addEventListener(\"ended\",this._handleTrackEnded),this._originMediaStreamTrack=e,this._muted&&(this._originMediaStreamTrack.enabled=!1),this.processor&&this._processorContext&&this.processor.updateInput({track:e,context:this._processorContext}),this._mediaStreamTrack!==this._source.outputTrack?(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await yT(this,BA.NEED_REPLACE_TRACK,this)):this._source.updateTrack(this._originMediaStreamTrack),this._getOriginVolumeLevel&&this._source.updateOriginTrack(e))}renewMediaStreamTrack(e){return cg.resolve(void 0)}pipe(e){if(this._bypassWebAudio)throw new Kg(Hg.INVALID_OPERATION,\"Can not process AudioTrack when bypassWebAudio set to true.\");if(this.processor===e)return e;if(e._source)throw new Kg(Hg.INVALID_OPERATION,\"Processor \".concat(e.name,\" already piped, please call unpipe beforehand.\"));return this.unpipe(),this.processor=e,this.processor._source=this,e.updateInput({track:this._originMediaStreamTrack,node:this._source.processSourceNode,context:this.processorContext}),e}unpipe(){var e;if(!this.processor)return;const t=this.processor;null===(e=this._source.processSourceNode)||void 0===e||e.disconnect(),this.processor._source=!1,this.processor=void 0,t.reset()}bindProcessorDestinationEvents(e){e.on(tb.ON_TRACK,(async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(!1),this._source.processedNode=this._source.createMediaStreamSourceNode(e),await yT(this,BA.NEED_REPLACE_TRACK,this)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await yT(this,BA.NEED_REPLACE_TRACK,this))})),e.on(tb.ON_NODE,(e=>{this._source.processedNode=e}))}unbindProcessorDestinationEvents(e){e.removeAllListeners(tb.ON_TRACK),e.removeAllListeners(tb.ON_NODE)}bindProcessorContextEvents(e){e.on(ib.REQUEST_CONSTRAINTS,(async e=>{e(this._originMediaStreamTrack.getSettings())}))}unbindProcessorContextEvents(e){e.removeAllListeners(ib.REQUEST_CONSTRAINTS)}initWebAudio(){return this._trackSource instanceof Xb&&(this._trackSource=new Cb(this._mediaStreamTrack,!1,this._getOriginVolumeLevel?this._mediaStreamTrack:void 0)),this._trackSource}initProcessor(){const e=new Jb(this._source.context,this.getTrackId(),\"local\"),t=new zb(e);return this._processorContext=e,this._processorDestination=t,this.bindProcessorContextEvents(e),this.bindProcessorDestinationEvents(t),this._source.on(zA.UPDATE_SOURCE,(()=>{this.processor&&this.processor.updateInput({node:this._source.processSourceNode,context:e})})),this._useAudioElement&&(this._useAudioElement=!1,this.isPlaying&&(Gb.stop(this.getTrackId()),this._source.play()),yT(this,BA.NEED_REPLACE_MIXING_TRACK,this).then((()=>{jC.debug(\"[\".concat(this.getTrackId(),\"] replace from origin track to web audio track success\"))})).catch((e=>{jC.warning(\"[\".concat(this.getTrackId(),\"] replace from origin track to web audio track failed\"),e)}))),{processorContext:e,processorDestination:t}}}DI([$C({argsMap:(e,t)=>[e.getTrackId(),t],throttleTime:300}),PI(\"design:type\",Function),PI(\"design:paramtypes\",[Number]),PI(\"design:returntype\",void 0)],ew.prototype,\"setVolume\",null),DI([$C({argsMap:(e,t)=>[e.getTrackId(),t]}),Wb(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[String]),PI(\"design:returntype\",cg)],ew.prototype,\"setPlaybackDevice\",null),DI([_S(\"LocalAudioTrack\",\"_enabledMutex\"),$C({argsMap:(e,t)=>[e.getTrackId(),t]}),Wb(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[Boolean,Object,Boolean]),PI(\"design:returntype\",cg)],ew.prototype,\"setEnabled\",null),DI([_S(\"LocalAudioTrack\",\"_enabledMutex\"),$C({argsMap:(e,t)=>[e.getTrackId(),t]}),Wb(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[Boolean]),PI(\"design:returntype\",cg)],ew.prototype,\"setMuted\",null),DI([Wb(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[]),PI(\"design:returntype\",Object)],ew.prototype,\"getStats\",null),DI([Wb(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[Object,Number]),PI(\"design:returntype\",void 0)],ew.prototype,\"setAudioFrameCallback\",null),DI([$C({argsMap:e=>[e.getTrackId()]}),Wb(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[]),PI(\"design:returntype\",void 0)],ew.prototype,\"play\",null),DI([$C({argsMap:e=>[e.getTrackId()]}),Wb(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[]),PI(\"design:returntype\",void 0)],ew.prototype,\"stop\",null),DI([$C({argsMap:e=>[e.getTrackId()]}),PI(\"design:type\",Function),PI(\"design:paramtypes\",[]),PI(\"design:returntype\",void 0)],ew.prototype,\"close\",null),DI([$C({argsMap:(e,t)=>[e.getTrackId(),t.name]}),PI(\"design:type\",Function),PI(\"design:paramtypes\",[Object]),PI(\"design:returntype\",Object)],ew.prototype,\"pipe\",null),DI([$C({argsMap:e=>[e.getTrackId()]}),PI(\"design:type\",Function),PI(\"design:paramtypes\",[]),PI(\"design:returntype\",void 0)],ew.prototype,\"unpipe\",null);class tw extends ew{get __className__(){return\"MicrophoneAudioTrack\"}constructor(e,t,i,n){super(e,t.encoderConfig?xA(t.encoderConfig):{},n,RC(\"GET_VOLUME_OF_MUTED_AUDIO_TRACK\")),sh(this,\"_config\",void 0),sh(this,\"_deviceName\",\"default\"),sh(this,\"_constraints\",void 0),sh(this,\"_originalConstraints\",void 0),sh(this,\"_enabled\",!0),this._config=t,this._constraints=i,this._originalConstraints=i,this._deviceName=e.label,\"boolean\"==typeof t.bypassWebAudio&&(this._bypassWebAudio=t.bypassWebAudio),(Mg()||Ug())&&_b.bindInterruptDetectorTrack(this)}async setDevice(e){if(jC.info(\"[\".concat(this.getTrackId(),\"] start set device to \").concat(e)),this._enabled)try{const t=await kb.getDeviceById(e),i={};i.audio=$b({},this._constraints),i.audio.deviceId={exact:e},this._originMediaStreamTrack.stop();let n=null;try{n=await Nb(i,this.getTrackId())}catch(e){throw jC.error(\"[\".concat(this.getTrackId(),\"] setDevice failed\"),e.toString()),n=await Nb({audio:this._constraints},this.getTrackId()),await this._updateOriginMediaStreamTrack(n.getAudioTracks()[0],!1),e}await this._updateOriginMediaStreamTrack(n.getAudioTracks()[0],!1),this._deviceName=t.label,this._config.microphoneId=e,this._constraints.deviceId={exact:e}}catch(e){throw jC.error(\"[\".concat(this.getTrackId(),\"] setDevice error\"),e.toString()),e}else try{const t=await kb.getDeviceById(e);this._deviceName=t.label,this._config.microphoneId=e,this._constraints.deviceId={exact:e}}catch(e){throw jC.error(\"[\".concat(this.getTrackId(),\"] setDevice error\"),e.toString()),e}jC.info(\"[\".concat(this.getTrackId(),\"] set device to \").concat(e,\" success\"))}async setEnabled(e,t,i){if(t)return jC.debug(\"[\".concat(this.getTrackId(),\"] setEnabled false (do not close microphone)\")),await super._setEnabled(e);if(!i){if(e===this._enabled)return;this.stateCheck(\"enabled\",e)}if(jC.info(\"[\".concat(this.getTrackId(),\"] start setEnabled\"),e),!e){var n;this._originMediaStreamTrack.onended=null,this._originMediaStreamTrack.stop(),null===(n=this._source.clonedTrack)||void 0===n||n.stop(),i||(this._enabled=!1);try{await yT(this,BA.NEED_DISABLE_TRACK,this)}catch(e){throw jC.error(\"[\".concat(this.getTrackId(),\"] setEnabled false failed\"),e.toString()),e}return}const r=$b({},this._constraints),s=kb.searchDeviceIdByName(this._deviceName);s&&!r.deviceId&&(r.deviceId=s);try{i||(this._enabled=!0);const e=await Nb({audio:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getAudioTracks()[0],!1),await yT(this,BA.NEED_ENABLE_TRACK,this)}catch(e){throw i||(this._enabled=!1),jC.error(\"[\".concat(this.getTrackId(),\"] setEnabled true failed\"),e.toString()),e}jC.info(\"[\".concat(this.getTrackId(),\"] setEnabled success\"))}close(){super.close(),(Mg()||Ug())&&_b.unbindInterruptDetectorTrack(this)}onTrackEnded(){if((Og()||Vg())&&this._enabled&&!this._isClosed&&_b.duringInterruption){const e=async()=>{_b.off(vA.IOS_INTERRUPTION_END,e),this._enabled&&!this._isClosed&&(jC.debug(\"[\".concat(this.getTrackId(),\"] try capture microphone media device for interrupted iOS device.\")),await this.setEnabled(!1),await this.setEnabled(!0))};_b.on(vA.IOS_INTERRUPTION_END,e)}else jC.debug(\"[\".concat(this.getTrackId(),\"] track ended\")),this.safeEmit(YA.TRACK_ENDED)}async renewMediaStreamTrack(e){const t=e||this._constraints,i=kb.searchDeviceIdByName(this._deviceName);if(i&&!t.deviceId&&(t.deviceId=i),this._constraints=t,this._enabled){this._originMediaStreamTrack.stop();const e=await Nb({audio:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getAudioTracks()[0],!0)}}bindProcessorContextEvents(e){super.bindProcessorContextEvents(e),e.on(ib.REQUEST_UPDATE_CONSTRAINTS,(async(e,t,i)=>{try{const i=Object.assign({},this._originalConstraints,...e);await this.renewMediaStreamTrack(i),t()}catch(e){i(e)}}))}unbindProcessorContextEvents(e){super.unbindProcessorContextEvents(e),e.removeAllListeners(ib.REQUEST_UPDATE_CONSTRAINTS)}}DI([$C({argsMap:(e,t)=>[e.getTrackId(),t]}),Wb(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[String]),PI(\"design:returntype\",cg)],tw.prototype,\"setDevice\",null),DI([_S(\"MicrophoneAudioTrack\",\"_enabledMutex\"),$C({argsMap:(e,t,i)=>[e.getTrackId(),t,i]}),Wb(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[Boolean,Boolean,Boolean]),PI(\"design:returntype\",cg)],tw.prototype,\"setEnabled\",null),DI([$C({argsMap:e=>[e.getTrackId()]}),PI(\"design:type\",Function),PI(\"design:paramtypes\",[]),PI(\"design:returntype\",void 0)],tw.prototype,\"close\",null);class iw extends ew{get __className__(){return\"BufferSourceAudioTrack\"}constructor(e,t,i,n){super(t.createOutputTrack(),i,n),sh(this,\"source\",void 0),sh(this,\"_bufferSource\",void 0),this._useAudioElement=!1,this.source=e,this._bufferSource=t,this._bufferSource.on(zA.AUDIO_SOURCE_STATE_CHANGE,(e=>{this.safeEmit(YA.SOURCE_STATE_CHANGE,e)}));try{this._mediaStreamTrack=this._source.createOutputTrack()}catch(e){}}get currentState(){return this._bufferSource.currentState}get duration(){return this._bufferSource.duration}get playbackSpeed(){return this._bufferSource.playbackSpeed}getCurrentTime(){return this._bufferSource.currentTime}startProcessAudioBuffer(e){e&&this._bufferSource.updateOptions(e),this._bufferSource.startProcessAudioBuffer()}pauseProcessAudioBuffer(){this._bufferSource.pauseProcessAudioBuffer()}seekAudioBuffer(e){this._bufferSource.seekAudioBuffer(e)}resumeProcessAudioBuffer(){this._bufferSource.resumeProcessAudioBuffer()}stopProcessAudioBuffer(){this._bufferSource.stopProcessAudioBuffer()}close(){this.source=null,this._bufferSource.destroy(),super.close()}setAudioBufferPlaybackSpeed(e){zg(e,\"speed\",0),this._bufferSource.setAudioBufferPlaybackSpeed(e)}}DI([$C({argsMap:(e,t)=>[e.getTrackId(),t,e.duration]}),Wb(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[Object]),PI(\"design:returntype\",void 0)],iw.prototype,\"startProcessAudioBuffer\",null),DI([$C({argsMap:e=>[e.getTrackId()]}),Wb(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[]),PI(\"design:returntype\",void 0)],iw.prototype,\"pauseProcessAudioBuffer\",null),DI([$C({argsMap:e=>[e.getTrackId()]}),Wb(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[Number]),PI(\"design:returntype\",void 0)],iw.prototype,\"seekAudioBuffer\",null),DI([$C({argsMap:e=>[e.getTrackId()]}),Wb(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[]),PI(\"design:returntype\",void 0)],iw.prototype,\"resumeProcessAudioBuffer\",null),DI([$C({argsMap:e=>[e.getTrackId()]}),Wb(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[]),PI(\"design:returntype\",void 0)],iw.prototype,\"stopProcessAudioBuffer\",null),DI([$C({argsMap:e=>[e.getTrackId()]}),PI(\"design:type\",Function),PI(\"design:paramtypes\",[]),PI(\"design:returntype\",void 0)],iw.prototype,\"close\",null),DI([$C({argsMap:e=>[e.getTrackId()]}),Wb(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[Number]),PI(\"design:returntype\",void 0)],iw.prototype,\"setAudioBufferPlaybackSpeed\",null);class nw extends ew{get __className__(){return\"MixingAudioTrack\"}get isActive(){for(const e of this.trackList)if(e._enabled&&!e._isClosed&&!e.muted)return!0;return!1}constructor(){const e=mb().createMediaStreamDestination();super(e.stream.getAudioTracks()[0],void 0,nS(8,\"track-mix-\")),sh(this,\"trackList\",void 0),sh(this,\"destNode\",void 0),this._useAudioElement=!1;try{this._mediaStreamTrack=this._source.createOutputTrack()}catch(e){}this.destNode=e,this.trackList=[]}hasAudioTrack(e){return-1!==this.trackList.indexOf(e)}addAudioTrack(e){-1===this.trackList.indexOf(e)?(jC.debug(\"add \".concat(e.getTrackId(),\" to mixing track\")),e._source.outputNode.connect(this.destNode),this.trackList.push(e),this.updateEncoderConfig()):jC.debug(\"track \".concat(e.getTrackId(),\" is already added\"))}removeAudioTrack(e){if(-1!==this.trackList.indexOf(e)){jC.debug(\"remove \".concat(e.getTrackId(),\" from mixing track\"));try{e._source.outputNode.disconnect(this.destNode)}catch(e){}WT(this.trackList,e),this.updateEncoderConfig()}}updateEncoderConfig(){const e={};this.trackList.forEach((t=>{t._encoderConfig&&((t._encoderConfig.bitrate||0)>(e.bitrate||0)&&(e.bitrate=t._encoderConfig.bitrate),(t._encoderConfig.sampleRate||0)>(e.sampleRate||0)&&(e.sampleRate=t._encoderConfig.sampleRate),(t._encoderConfig.sampleSize||0)>(e.sampleSize||0)&&(e.sampleSize=t._encoderConfig.sampleSize),t._encoderConfig.stereo&&(e.stereo=!0))})),this._encoderConfig=e}_updateRtpTransceiver(e){this._rtpTransceiver!==e&&(this._rtpTransceiver=e,this.trackList.forEach((t=>{t instanceof nw?t.emit(KA.TRANSCEIVER_UPDATED,e):t._updateRtpTransceiver(e)})))}}function rw(e){const t={};e.facingMode&&(t.facingMode=e.facingMode),e.cameraId&&(t.deviceId={exact:e.cameraId});const i=LA(e.encoderConfig);return null!=i.width&&(t.width=i.width),null!=i.height&&(t.height=i.height),!Bg()&&i.frameRate&&(t.frameRate=i.frameRate),Sg().name===Eg.EDGE&&\"object\"==typeof t.frameRate&&(t.frameRate.max=60),wg()&&(t.frameRate={ideal:30,max:30}),t}function sw(e){const t={};if(Bg()||(void 0!==e.AGC&&(t.autoGainControl=e.AGC),void 0!==e.AEC&&(t.echoCancellation=e.AEC),void 0!==e.ANS&&(t.noiseSuppression=e.ANS,Ag()&&e.ANS&&(t.googHighpassFilter=e.ANS))),e.encoderConfig){const i=xA(e.encoderConfig);t.channelCount=i.stereo?2:1,t.sampleRate=i.sampleRate,t.sampleSize=i.sampleSize}return e.microphoneId&&(t.deviceId={exact:e.microphoneId}),Gg()&&(t.sampleRate=void 0),t}class ow extends Rb{set currentState(e){e!==this._currentState&&(this._currentState=e,this.safeEmit(zA.AUDIO_SOURCE_STATE_CHANGE,this._currentState))}get currentState(){return this._currentState}constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),sh(this,\"audioBuffer\",void 0),sh(this,\"sourceNode\",void 0),sh(this,\"startPlayTime\",0),sh(this,\"startPlayOffset\",0),sh(this,\"pausePlayTime\",0),sh(this,\"options\",void 0),sh(this,\"currentLoopCount\",0),sh(this,\"currentPlaybackSpeed\",100),sh(this,\"_currentState\",\"stopped\"),this.audioBuffer=e,this.options=t,this.startPlayOffset=this.options.startPlayTime||0}createWebAudioDiagram(){return this.context.createGain()}get duration(){return this.audioBuffer?this.audioBuffer.duration:0}get playbackSpeed(){return this.currentPlaybackSpeed}get currentTime(){return this.audioBuffer?\"stopped\"===this.currentState?0:\"paused\"===this.currentState?this.pausePlayTime:((this.context.currentTime-this.startPlayTime)*(this.playbackSpeed/100)+this.startPlayOffset)%this.audioBuffer.duration:0}updateOptions(e){\"stopped\"===this.currentState?(this.options=e,this.startPlayOffset=this.options.startPlayTime||0):jC.warning(\"can not set audio source options\")}startProcessAudioBuffer(){this.sourceNode&&this.stopProcessAudioBuffer(),this.sourceNode=this.createSourceNode(),this.startSourceNode(),this.currentState=\"playing\"}pauseProcessAudioBuffer(){this.sourceNode&&\"playing\"===this.currentState&&(this.pausePlayTime=this.currentTime,this.sourceNode.onended=null,this.sourceNode.stop(),this.sourceNode.buffer=null,this.sourceNode=this.createSourceNode(),this.currentState=\"paused\")}seekAudioBuffer(e){this.sourceNode&&(this.sourceNode.onended=null,\"playing\"===this.currentState&&this.sourceNode.stop(),this.sourceNode=this.createSourceNode(),\"playing\"===this.currentState?(this.startPlayOffset=e,this.startSourceNode()):\"paused\"===this.currentState&&(this.pausePlayTime=e))}resumeProcessAudioBuffer(){\"paused\"===this.currentState&&this.sourceNode&&(this.startPlayOffset=this.pausePlayTime,this.pausePlayTime=0,this.startSourceNode(),this.currentState=\"playing\")}stopProcessAudioBuffer(){if(this.sourceNode){this.sourceNode.onended=null;try{this.sourceNode.stop()}catch(e){}this.reset()}}destroy(){this.audioBuffer=null,super.destroy()}setAudioBufferPlaybackSpeed(e){this.sourceNode&&(\"playing\"===this.currentState&&(this.startPlayOffset=this.currentTime,this.startPlayTime=this.context.currentTime),this.sourceNode.playbackRate.value=e/100),this.currentPlaybackSpeed=e}startSourceNode(){this.sourceNode&&this.sourceNode.buffer&&(this.sourceNode.start(0,this.startPlayOffset),this.startPlayTime=this.context.currentTime,this.sourceNode.onended=this.handleSourceNodeEnded.bind(this))}createSourceNode(){const e=this.context.createBufferSource();return e.buffer=this.audioBuffer,e.loop=!!this.options.loop,e.connect(this.outputNode),e.playbackRate.value=this.currentPlaybackSpeed/100,e}handleSourceNodeEnded(){if(this.currentLoopCount+=1,this.options.cycle&&this.options.cycle>this.currentLoopCount)return this.startPlayOffset=0,this.sourceNode=void 0,void this.startProcessAudioBuffer();this.reset()}reset(){this.startPlayOffset=this.options.startPlayTime||0,this.currentState=\"stopped\",this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=void 0),this.currentLoopCount=0}}const aw=new Map;async function cw(e,t){let i=null;if(\"string\"==typeof e){const t=aw.get(e);if(t)return jC.debug(\"use cached audio resource: \",e),t;try{i=(await fS((()=>sC.get(e,{responseType:\"arraybuffer\"})),void 0,void 0,{maxRetryCount:3})).data}catch(e){throw new Kg(Hg.FETCH_AUDIO_FILE_FAILED,e.toString())}}else{const t=new cg(((t,i)=>{const n=new FileReader;n.onload=e=>{e.target?t(e.target.result):i(new Kg(Hg.READ_LOCAL_AUDIO_FILE_ERROR))},n.onerror=()=>{i(new Kg(Hg.READ_LOCAL_AUDIO_FILE_ERROR))},n.readAsArrayBuffer(e)}));i=await t}const n=await function(e){const t=mb();return new cg(((i,n)=>{t.decodeAudioData(e,(e=>{i(e)}),(e=>{n(new Kg(Hg.DECODE_AUDIO_FILE_FAILED,e.toString()))}))}))}(i);return\"string\"==typeof e&&t&&aw.set(e,n),n}const dw=e=>{const t=document.createElement(\"canvas\");return t.width=2,t.height=2,new cg(((i,n)=>{t.toBlob((async e=>{if(t.remove(),e){const n=await lw(e);i({buffer:n,width:t.width,height:t.height})}else n(new Kg(Hg.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED))}),e,1)}))},lw=async e=>{const t=await e.arrayBuffer();return new Uint8Array(t)};function uw(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function hw(e){for(var t=1;t \").concat(e)),this._videoElementStatus=e)}get videoState(){return this._videoState}set videoState(e){var t;e!==this._videoState&&(jC.debug(\"[\".concat(this.trackId,\"] video-status change \").concat(this._videoState,\" => \").concat(e)),this._videoState=e,null===(t=this.onVideoStateChanged)||void 0===t||t.call(this,this.videoState))}constructor(e){sh(this,\"trackId\",void 0),sh(this,\"config\",void 0),sh(this,\"onFirstVideoFrameDecoded\",void 0),sh(this,\"onVideoStateChanged\",void 0),sh(this,\"freezeTimeCounterList\",[]),sh(this,\"renderFreezeAccTime\",0),sh(this,\"isKeepLastFrame\",!1),sh(this,\"timeUpdatedCount\",0),sh(this,\"freezeTime\",0),sh(this,\"playbackTime\",0),sh(this,\"lastTimeUpdatedTime\",0),sh(this,\"autoplayFailed\",!1),sh(this,\"videoTrack\",void 0),sh(this,\"videoElement\",void 0),sh(this,\"cacheVideoElement\",void 0),sh(this,\"_videoState\",ob.VideoStateStopped),sh(this,\"videoElementCheckInterval\",void 0),sh(this,\"videoElementFreezeTimeout\",void 0),sh(this,\"_videoElementStatus\",sb.NONE),sh(this,\"isGettingVideoDimensions\",!1),sh(this,\"startGetVideoDimensions\",(()=>{const e=()=>{if(this.isGettingVideoDimensions=!0,this.videoElement.videoWidth*this.videoElement.videoHeight>4)return jC.debug(\"[\".concat(this.trackId,\"] current video dimensions:\"),this.videoElement.videoWidth,this.videoElement.videoHeight),void(this.isGettingVideoDimensions=!1);setTimeout(e,500)};!this.isGettingVideoDimensions&&e()})),sh(this,\"autoResumeAfterInterruption\",(()=>{this.videoTrack&&\"live\"===this.videoTrack.readyState&&\"running\"===_b.curState&&(jC.debug(\"[track-\".concat(this.trackId,\"] video element paused, auto resume for \").concat(Cg())),xg()?(this.videoElement.srcObject=null,this.videoElement.srcObject=new MediaStream([this.videoTrack]),this.videoElement.play()):(this.videoElement.pause(),this.videoElement.play()))})),sh(this,\"handleVideoEvents\",(e=>{switch(e.type){case\"play\":case\"playing\":this.startGetVideoDimensions(),this.videoElementStatus=sb.PLAYING;break;case\"loadeddata\":if(this.videoState=ob.VideoStateStarting,this.onFirstVideoFrameDecoded&&this.onFirstVideoFrameDecoded(),this.cacheVideoElement){try{this.cacheVideoElement.srcObject=null,this.cacheVideoElement.remove()}catch(e){}this.cacheVideoElement=void 0}break;case\"canplay\":this.videoElementStatus=sb.CANPLAY;break;case\"stalled\":this.videoElementStatus=sb.STALLED;break;case\"suspend\":this.videoElementStatus=sb.SUSPEND;break;case\"pause\":this.videoElementStatus=sb.PAUSED,Og()||Vg()||bg()&&this.autoplayFailed||!this.videoTrack||\"live\"!==this.videoTrack.readyState||(jC.debug(\"[track-\".concat(this.trackId,\"] video element paused, auto resume\")),this.videoElement.play());break;case\"waiting\":this.videoElementStatus=sb.WAITING;break;case\"abort\":this.videoElementStatus=sb.ABORT;break;case\"ended\":this.videoElementStatus=sb.ENDED;break;case\"emptied\":this.videoElementStatus=sb.EMPTIED;break;case\"error\":{this.videoElementStatus=sb.ERROR;const e=this.videoElement.error;e&&jC.error(\"[\".concat(this.trackId,\"] media error, code: \").concat(e.code,\", message: \").concat(e.message));break}case\"timeupdate\":{const e=performance.now();if(this.timeUpdatedCount+=1,this.timeUpdatedCount<10)return void(this.lastTimeUpdatedTime=e);const t=e-this.lastTimeUpdatedTime,i=this.lastTimeUpdatedTime;if(this.lastTimeUpdatedTime=e,Dw.lastVisibleTimeRC(\"VIDEO_FREEZE_DURATION\")&&(this.freezeTime+=t),this.playbackTime+=t;this.playbackTime>=6e3;){this.playbackTime-=6e3;const e=Math.min(6e3,this.freezeTime);this.freezeTimeCounterList.push(e),this.freezeTime=Math.max(0,this.freezeTime-6e3)}break}}})),sh(this,\"autoResumeAfterInterruptionOnIOS15_16\",(()=>{this.videoTrack&&\"live\"===this.videoTrack.readyState&&(jC.debug(\"[track-\".concat(this.trackId,\"] video element paused, auto resume for \").concat(Cg())),xg()?(this.videoElement.srcObject=null,this.videoElement.srcObject=new MediaStream([this.videoTrack]),this.videoElement.play()):(this.videoElement.pause(),this.videoElement.play()))})),this.trackId=e.trackId,this.config=e,e.element instanceof HTMLVideoElement?this.videoElement=e.element:this.videoElement=document.createElement(\"video\"),_b.on(vA.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),_b.on(vA.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16)}getVideoElement(){return this.videoElement}getContainerElement(){var e;return null!==(e=this.videoElement.parentElement)&&void 0!==e?e:void 0}updateConfig(e){this.config=e,this.trackId=e.trackId,e.element!==this.videoElement&&(this.destroy(),this.videoElement=e.element),this.videoTrack&&this.initVideoElement()}updateVideoTrack(e){this.videoTrack!==e&&(this.videoTrack=e,this.initVideoElement())}play(e){const t=this.videoElement.play();t&&t.catch&&t.catch((t=>{e&&Bb(e,\"video\",t.message,this.trackId),\"NotAllowedError\"===t.name?(jC.warning(\"detected video element autoplay failed\",t),this.autoplayFailed=!0,this.handleAutoPlayFailed()):jC.warning(\"[\".concat(this.trackId,\"] play warning: \"),t)}));const i=Sg();if((\"Safari\"===i.name&&15===Number(i.version)||Mg())&&t&&t.then){const e=()=>{this.config.mirror&&(this.videoElement.style.transform=\"rotateY(180deg)\")};t.then(e).catch(e)}}getCurrentFrame(){const e=document.createElement(\"canvas\");e.width=this.videoElement.videoWidth,e.height=this.videoElement.videoHeight;const t=e.getContext(\"2d\");if(!t)return jC.error(\"create canvas context failed!\"),new ImageData(2,2);t.drawImage(this.videoElement,0,0,e.width,e.height);const i=t.getImageData(0,0,e.width,e.height);return e.remove(),i}async getCurrentFrameToUint8Array(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;const i=document.createElement(\"canvas\");i.width=this.videoElement.videoWidth,i.height=this.videoElement.videoHeight;const n=i.getContext(\"2d\");return n?(n.drawImage(this.videoElement,0,0,i.width,i.height),new cg(((n,r)=>{i.toBlob((async e=>{if(i.remove(),e){const t=await lw(e);n({buffer:t,width:i.width,height:i.height})}else r(new Kg(Hg.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED))}),e,t<0?.1:t>1?1:t)}))):await dw(e)}destroy(){_b.off(vA.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),_b.off(vA.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16),this.videoElement.srcObject=null,this.resetVideoElement(),this.freezeTimeCounterList=[],this.videoState=ob.VideoStateStopped}initVideoElement(){if(this.videoElementStatus=sb.INIT,!this.videoElementCheckInterval&&(_w.forEach((e=>{this.videoElement.addEventListener(e,this.handleVideoEvents)})),this.videoElementCheckInterval=window.setInterval((()=>{(function(e){return e!==document.body&&document.body.contains(e)})(this.videoElement)||(this.videoElementStatus=sb.DESTROYED)}),1e3),RC(\"ENABLE_VIDEO_FRAME_CALLBACK\"))){var e,t;let i;const n=()=>{\"visible\"===document.visibilityState&&(document.removeEventListener(\"visibilitychange\",n),this.videoElementFreezeTimeout=window.setTimeout(r,RC(\"VIDEO_FREEZE_DURATION\")))},r=()=>{this.videoElementFreezeTimeout=void 0,this.videoState===ob.VideoStateDecoding&&(\"visible\"===document.visibilityState?this.videoState=ob.VideoStateFrozen:document.addEventListener(\"visibilitychange\",n))},s=(e,t)=>{if(this.videoElementStatus===sb.PLAYING){if(i){const e=t.presentationTime-i.presentationTime;this.videoState===ob.VideoStateStarting&&(this.videoState=ob.VideoStateDecoding),this.videoState===ob.VideoStateDecoding&&this.onVideoStateChanged&&(this.videoElementFreezeTimeout&&window.clearTimeout(this.videoElementFreezeTimeout),this.videoElementFreezeTimeout=window.setTimeout(r,RC(\"VIDEO_FREEZE_DURATION\"))),eRC(\"VIDEO_FREEZE_DURATION\")&&Dw.lastVisibleTime>=Dw.lastHiddenTime&&i.timestamp>Dw.lastVisibleTime&&i.timestamp>Dw.lastHiddenTime&&(this.renderFreezeAccTime+=e)}i=hw(hw({},t),{},{timestamp:e})}var n,o;RC(\"ENABLE_VIDEO_FRAME_CALLBACK\")&&(null===(n=(o=this.videoElement).requestVideoFrameCallback)||void 0===n||n.call(o,s))};null===(e=(t=this.videoElement).requestVideoFrameCallback)||void 0===e||e.call(t,s)}this.videoElement.controls=!1,this.videoElement.setAttribute(\"playsinline\",\"\"),Gg()&&(this.videoElement.poster=\"noposter\");const i=Sg();if(\"Safari\"===i.name&&15===Number(i.version)||Mg()||!this.config.mirror||(this.videoElement.style.transform=\"rotateY(180deg)\"),this.config.fit?this.videoElement.style.objectFit=this.config.fit:this.videoElement.style.objectFit=\"cover\",this.videoElement.setAttribute(\"muted\",\"\"),this.videoElement.muted=!0,this.videoElement.srcObject&&this.videoElement.srcObject instanceof MediaStream){this.videoElement.srcObject.getVideoTracks()[0]!==this.videoTrack&&(this.videoElement.srcObject=this.videoTrack?new MediaStream([this.videoTrack]):null,wg()&&this.videoElement.load())}else this.videoElement.srcObject=this.videoTrack?new MediaStream([this.videoTrack]):null,wg()&&this.videoElement.load();const n=this.videoElement.play();void 0!==n&&n.catch((e=>{jC.debug(\"[\".concat(this.trackId,\"] playback interrupted\"),e.toString())}))}resetVideoElement(){_w.forEach((e=>{this.videoElement&&this.videoElement.removeEventListener(e,this.handleVideoEvents)})),this.videoElementCheckInterval&&(window.clearInterval(this.videoElementCheckInterval),this.videoElementCheckInterval=void 0),this.videoElementStatus=sb.NONE}handleAutoPlayFailed(){const e=t=>{t.preventDefault(),this.videoElement.play().then((()=>{jC.debug(\"[\".concat(this.trackId,\"] Video element for trackId:\").concat(this.trackId,\" autoplay resumed.\"))})).catch((e=>{jC.error(e)})),this.autoplayFailed=!1,Wg()?document.body.removeEventListener(\"click\",e,!0):(document.body.removeEventListener(\"touchstart\",e,!0),document.body.removeEventListener(\"mousedown\",e,!0))};Wg()?document.body.addEventListener(\"click\",e,!0):(document.body.addEventListener(\"touchstart\",e,!0),document.body.addEventListener(\"mousedown\",e,!0)),xb()}}const _w=[\"play\",\"playing\",\"loadeddata\",\"canplay\",\"pause\",\"stalled\",\"suspend\",\"waiting\",\"abort\",\"emptied\",\"ended\",\"timeupdate\",\"error\"];class Ew extends pw{constructor(e){super(e),sh(this,\"container\",void 0),sh(this,\"slot\",void 0),this.slot=e.element,this.updateConfig(e)}updateConfig(e){this.config=e,this.trackId=e.trackId;const t=e.element;t!==this.slot&&(this.destroy(),this.slot=t),this.createElements()}updateVideoTrack(e){this.videoTrack!==e&&(this.videoTrack=e,this.createElements())}play(e){var t;null!==(t=this.container)&&void 0!==t&&t.contains(this.videoElement)&&super.play(e)}getCurrentFrame(){var e;return null!==(e=this.container)&&void 0!==e&&e.contains(this.videoElement)?super.getCurrentFrame():new ImageData(2,2)}async getCurrentFrameToUint8Array(e){var t;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return null!==(t=this.container)&&void 0!==t&&t.contains(this.videoElement)?await super.getCurrentFrameToUint8Array(e,i):await dw(e)}destroy(){if(super.destroy(),this.videoElement.remove(),this.videoElement=document.createElement(\"video\"),this.container){try{this.container.remove(),this.slot.removeChild(this.container)}catch(e){}this.container=void 0}}createElements(){this.container||(this.container=document.createElement(\"div\")),this.container.id=\"agora-video-player-\".concat(this.trackId),this.container.style.width=\"100%\",this.container.style.height=\"100%\",this.container.style.position=\"relative\",this.container.style.overflow=\"hidden\",this.videoTrack?(this.container.style.backgroundColor=\"black\",RC(\"KEEP_LAST_FRAME\")&&this.isKeepLastFrame&&this.videoElement.paused&&this.resetVideoElement(),this.mountedVideoElement()):this.unmountedVideoElement(),this.slot.appendChild(this.container)}mountedVideoElement(){var e;!this.container||null!==(e=this.container)&&void 0!==e&&e.contains(this.videoElement)||this.container.appendChild(this.videoElement),super.initVideoElement(),this.videoElement.id=\"video_\".concat(this.trackId),this.videoElement.className=\"agora_video_player\",this.videoElement.style.width=\"100%\",this.videoElement.style.height=\"100%\",this.videoElement.style.position=\"absolute\",this.videoElement.style.left=\"0\",this.videoElement.style.top=\"0\"}unmountedVideoElement(){var e;if(null!==(e=this.container)&&void 0!==e&&e.contains(this.videoElement)){super.resetVideoElement();try{this.container&&this.container.removeChild(this.videoElement)}catch(e){}this.videoElement=document.createElement(\"video\")}}resetVideoElement(){var e;null!==(e=this.container)&&void 0!==e&&e.contains(this.videoElement)&&(super.resetVideoElement(),this.cacheVideoElement=this.videoElement,this.videoElement=document.createElement(\"video\"))}getContainerElement(){return this.container}}function mw(e){return new cg(((t,i)=>{let n=!1;const r=document.createElement(\"video\");r.setAttribute(\"autoplay\",\"\"),r.setAttribute(\"muted\",\"\"),r.muted=!0,r.autoplay=!0,r.setAttribute(\"playsinline\",\"\"),r.setAttribute(\"style\",\"position: fixed; top: 0; left: 0; width: 1px; height: 1px\"),document.body.appendChild(r);const s=Og()?\"canplay\":\"playing\";r.addEventListener(s,(()=>{const e=r.videoWidth,i=r.videoHeight;!e&&wg()||(n=!0,r.srcObject=null,r.remove(),t([e,i]))})),r.srcObject=new MediaStream([e]),r.play().catch(sS),setTimeout((()=>{n||(r.srcObject=null,r.remove(),t([r.videoWidth,r.videoHeight]))}),4e3)}))}const fw=async(e,t,i)=>{const n=function(e){const t=[];for(let i=0;i>8*i+4&15)+t.charAt(e>>8*i&15);return n}function n(e,t){const i=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(i>>16)<<16|65535&i}function r(e,t,i,r,s,o){return n(function(e,t){return e<>>32-t}(n(n(t,e),n(r,o)),s),i)}function s(e,t,i,n,s,o,a){return r(t&i|~t&n,e,t,s,o,a)}function o(e,t,i,n,s,o,a){return r(t&n|i&~n,e,t,s,o,a)}function a(e,t,i,n,s,o,a){return r(t^i^n,e,t,s,o,a)}function c(e,t,i,n,s,o,a){return r(i^(t|~n),e,t,s,o,a)}const d=function(e){let t;const i=1+(e.length+8>>6),n=new Array(16*i);for(t=0;t<16*i;t++)n[t]=0;for(t=0;t>2]|=e.charCodeAt(t)<>2]|=128<await fw(e.buffer,t,i);function Tw(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function Sw(e){for(var t=1;tthis._previousVideoVisibleStatus=void 0)),sh(this,\"_encoderConfig\",void 0),sh(this,\"_scalabilityMode\",{numSpatialLayers:1,numTemporalLayers:1}),sh(this,\"_optimizationMode\",void 0),sh(this,\"_videoHeight\",void 0),sh(this,\"_videoWidth\",void 0),sh(this,\"_forceBitrateLimit\",void 0),sh(this,\"_enabled\",!0),sh(this,\"processorDestination\",void 0),sh(this,\"_processorContext\",void 0),bg()){const{width:t,height:i}=e.getSettings();this._videoWidth=t,this._videoHeight=i}else this.updateMediaStreamTrackResolution();if(this._encoderConfig=t,this._scalabilityMode=i,this._optimizationMode=n,this._hints=s||[],-1===this._hints.indexOf(jA.SCREEN_TRACK))this.updateBitrateFromProfile();else if(function(e,t,i){const n=Sg();return!(n.name!==e||!n.osVersion)&&(i?Number(n.version)>=t&&Number(n.version)<=i:Number(n.version)===t)}(Eg.CHROME,115)&&-1!==Rg().indexOf(\"Windows\")){const t=function(e,t){if(\"VideoFrame\"in window&&\"TransformStream\"in window&&IA().supportWebRTCInsertableStream){const i=new MediaStreamTrackProcessor(e),n=new MediaStreamTrackGenerator({kind:\"video\"});let r,s,o=Date.now();const a=()=>{c&&(clearInterval(c),c=void 0),r&&(r.close(),r=void 0),e.stop(),s=void 0,n.removeEventListener(\"ended\",a)};let c=window.setInterval((()=>{if(s&&r&&Date.now()-o>(null!=t?t:1e3))try{\"live\"===n.readyState?s.enqueue(r.clone()):a()}catch(e){a()}}),null!=t?t:1e3);const d=new TransformStream({transform:(e,t)=>{\"live\"===n.readyState?(s=t,o=Date.now(),void 0===r?(r=e,t.enqueue(e.clone())):(t.enqueue(r),r=e)):e.close()}});return n.addEventListener(\"ended\",a),i.readable.pipeThrough(d).pipeTo(n.writable),n}}(e);t&&(jC.info(\"local screen video track begin to inject frame\"),this._mediaStreamTrack=t)}t&&-1!==this._hints.indexOf(jA.CUSTOM_TRACK)&&this.setEncoderConfiguration(t),this._processorContext=new qb(this.getTrackId(),\"local\"),this.processorDestination=new Yb(this.processorContext),this.bindProcessorDestinationEvents()}play(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(\"string\"==typeof e){const t=document.getElementById(e);t?e=t:(jC.warning(\"[\".concat(this.getTrackId(),'] can not find \"#').concat(e,'\" element, use document.body')),e=document.body)}jC.debug(\"[\".concat(this.getTrackId(),\"] start video playback in \").concat(e instanceof HTMLVideoElement?\"HTMLVideoElement\":\"HTMLElement\"),JSON.stringify(t));const i=Sw(Sw(Sw({},this._getDefaultPlayerConfig()),t),{},{trackId:this.getTrackId(),element:e});this._player?this._player.updateConfig(i):(e instanceof HTMLVideoElement?this._player=new pw(i):this._player=new Ew(i),this._player.updateVideoTrack(this._mediaStreamTrack)),this._player.play(),this._videoVisibleTimer&&window.clearInterval(this._videoVisibleTimer),this._clearPreviousVideoVisibleStatus(),this._videoVisibleTimer=window.setInterval((()=>{try{const e=this.getVideoElementVisibleStatus();this.safeEmit(YA.VIDEO_ELEMENT_VISIBLE_STATUS,e)}catch(e){}}),RC(\"CHECK_VIDEO_VISIBLE_INTERVAL\"))}stop(){this._player&&(this._videoVisibleTimer&&(window.clearInterval(this._videoVisibleTimer),this._videoVisibleTimer=null),this._statsTimer&&(this.isUseScaleResolutionDownBy=!1,window.clearInterval(this._statsTimer),this._statsTimer=null),this._clearPreviousVideoVisibleStatus(),this._player.destroy(),this._player=void 0,jC.debug(\"[\".concat(this.getTrackId(),\"] stop video playback\")))}async setEnabled(e,t){if(!t){if(e===this._enabled)return;this.stateCheck(\"enabled\",e)}if(jC.info(\"[\".concat(this.getTrackId(),\"] start setEnabled\"),e),!e){this._originMediaStreamTrack.enabled=!1;try{await yT(this,BA.NEED_DISABLE_TRACK,this)}catch(e){throw jC.error(\"[\".concat(this.getTrackId(),\"] setEnabled to false error\"),e.toString()),e}return t||(this._enabled=!1),void jC.info(\"[\".concat(this.getTrackId(),\"] setEnabled to false success\"))}this._originMediaStreamTrack.enabled=!0;try{await yT(this,BA.NEED_ENABLE_TRACK,this)}catch(e){throw jC.error(\"[\".concat(this.getTrackId(),\"] setEnabled to true error\"),e.toString()),e}jC.info(\"[\".concat(this.getTrackId(),\"] setEnabled to true success\")),t||(this._enabled=!0)}async setMuted(e){e!==this._muted&&(this.stateCheck(\"muted\",e),this._muted=e,this._originMediaStreamTrack.enabled=!e,jC.debug(\"[\".concat(this.getTrackId(),\"] start set muted: \").concat(e)),e?await yT(this,BA.NEED_MUTE_TRACK,this):await yT(this,BA.NEED_UNMUTE_TRACK,this))}async setEncoderConfiguration(e,t){if(!this._enabled)throw new Kg(Hg.TRACK_IS_DISABLED,\"can not set encoder configuration when track is disabled\");if(\"720p_auto\"===e?this.startMonitorStats():this._statsTimer&&(window.clearInterval(this._statsTimer),this._statsTimer=null),e=LA(e),this._forceBitrateLimit&&(e.bitrateMax=this._forceBitrateLimit.max_bitrate?this._forceBitrateLimit.max_bitrate:e.bitrateMax,e.bitrateMin=this._forceBitrateLimit.min_bitrate?this._forceBitrateLimit.min_bitrate:e.bitrateMin),e.width||e.height||e.frameRate){const t=rw({encoderConfig:e});(bg()||Og()||Vg())&&(t.deviceId=void 0),jC.debug(\"[\".concat(this.getTrackId(),\"] setEncoderConfiguration applyConstraints\"),JSON.stringify(e),JSON.stringify(t));try{await this._originMediaStreamTrack.applyConstraints(t),this.updateMediaStreamTrackResolution()}catch(e){const t=new Kg(Hg.UNEXPECTED_ERROR,e.toString());throw jC.error(\"[\".concat(this.getTrackId(),\"] applyConstraints error\"),t.toString()),t}}this._encoderConfig=e,-1===this._hints.indexOf(jA.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await yT(this,BA.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(jC)}}getStats(){JT((()=>{jC.warning(\"[deprecated] LocalVideoTrack.getStats will be removed in the future, use AgoraRTCClient.getLocalVideoStats instead\")}),\"localVideoTrackGetStatsWarning\");const e=AT(this,BA.GET_STATS);return e||Sw({},QA)}async setBeautyEffect(e){jC.error(\"LocalVideoTrack.setBeautyEffect was deprecated, please migrate to agora-extension-beauty-effect\")}getCurrentFrameData(){return this._player?this._player.getCurrentFrame():new ImageData(2,2)}async getCurrentFrameImage(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return this._player?this._player.getCurrentFrameToUint8Array(e,t):await dw(e)}async setBitrateLimit(e){if(jC.debug(\"[\".concat(this.getTrackId(),\"] set bitrate limit, \").concat(JSON.stringify(e))),e){this._forceBitrateLimit=e,this._encoderConfig&&(this._encoderConfig.bitrateMax?this._encoderConfig.bitrateMax=this._encoderConfig.bitrateMax{let[t,i]=e;this._videoHeight=i,this._videoWidth=t})).catch(sS)}_updatePlayerSource(){this._player&&this._player.updateVideoTrack(this._mediaStreamTrack)}_getDefaultPlayerConfig(){return{fit:\"contain\"}}async setSenderConfiguration(e){if(!this._enabled)throw new Kg(Hg.TRACK_IS_DISABLED,\"can not set encoder configuration when track is disabled\");jC.debug(\"[\".concat(this.getTrackId(),\"] setSenderConfiguration applyConstraints\"),JSON.stringify(e)),e=LA(e),this._forceBitrateLimit&&(e.bitrateMax=this._forceBitrateLimit.max_bitrate?this._forceBitrateLimit.max_bitrate:e.bitrateMax,e.bitrateMin=this._forceBitrateLimit.min_bitrate?this._forceBitrateLimit.min_bitrate:e.bitrateMin),this._encoderConfig=e,-1===this._hints.indexOf(jA.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await yT(this,BA.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(jC)}}updateBitrateFromProfile(){if(!this._encoderConfig)return;const{width:e,height:t,frameRate:i}=this.getMediaStreamTrackSettings();if(!e||!t||!i)return;const{bitrateMax:n,bitrateMin:r}=this._encoderConfig;if(null==r||null==n){const{max:s,min:o}=function(e,t,i,n,r){const s=RC(\"BITRATE_ADAPTER_TYPE\");if(\"DEFAULT_BITRATE\"===s)return{min:n,max:r};if(void 0===r){var o;const a=Math.floor(200*Math.pow(i/15,.6)*Math.pow(e*t/640/360,.75));r=\"STANDARD_BITRATE\"===s?4*a:2*a,n=null!==(o=n)&&void 0!==o?o:a}else{var a;n=null!==(a=n)&&void 0!==a?a:Math.floor(r/10)}return{min:n,max:r}}(e,t,i,r,n);this._encoderConfig.bitrateMin=o,this._encoderConfig.bitrateMax=s,jC.debug(\"[\".concat(this.getTrackId(),\"] update bitrate from profile, [w: \").concat(e,\", h: \").concat(t,\", fps: \").concat(i,\"] => [brMax: \").concat(s,\", brMin: \").concat(o,\"]\"))}}getVideoElementVisibleStatus(){try{var e,t;const i=null==this||null===(e=this._player)||void 0===e?void 0:e.getContainerElement(),n={track:this,element:null==this||null===(t=this._player)||void 0===t?void 0:t.getVideoElement(),slot:null==i?void 0:i.parentElement},{element:r,slot:s}=n;if(this.isPlaying&&r instanceof HTMLVideoElement&&s instanceof HTMLElement){const e=rT.checkOneElementVisible(r),t=Object.assign({},e);if(t.visible!==this._previousVideoVisibleStatus){this._previousVideoVisibleStatus=t.visible;const e=eI.reportApiInvoke(null,{tag:pT.TRACER,name:hT.LOCAL_VIDEO_TRACK_GET_VIDEO_VISIBLE,options:[this.getTrackId()]});t.visible?e.onSuccess(\"Video is visible\"):e.onSuccess(\"Invisible because of \".concat(t.reason))}return t}return}catch(e){throw new Kg(Hg.GET_VIDEO_ELEMENT_VISIBLE_ERROR,e.message)}}async renewMediaStreamTrack(e){}pipe(e){if(this.processor===e)return e;if(e._source)throw new Kg(Hg.INVALID_OPERATION,\"Processor \".concat(e.name,\" already piped, please call unpipe beforehand.\"));return this.unpipe(),this.processor=e,this.processor._source=this,e.updateInput({track:this._originMediaStreamTrack,context:this.processorContext}),e}unpipe(){if(!this.processor)return;const e=this.processor;this.processor._source=void 0,this.processor=void 0,e.reset()}close(){super.close(),this.unbindProcessorDestinationEvents(),this.unbindProcessorContextEvents(),this.unpipe(),this.processorDestination._source&&this.processorDestination._source.unpipe()}clone(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],i=this._encoderConfig;e&&(i=Sw(Sw({},i),LA(e))),i=qT(i);const n=nS(8,\"track-video-cloned-\"),r=new Rw(t?this._mediaStreamTrack.clone():this._mediaStreamTrack,i,qT(this._scalabilityMode),this._optimizationMode,n,qT(this._hints));return e&&i&&r.setEncoderConfiguration(i),jC.debug(\"clone video track from \".concat(this.getTrackId(),\" to \").concat(n,\", clone \").concat(t)),r}async replaceTrack(e,t){if(!(e instanceof MediaStreamTrack))throw new Kg(Hg.INVALID_PARAMS,\"track should be an instance of MediaStreamTrack\");if(\"video\"!==e.kind)throw new Kg(Hg.INVALID_PARAMS,\"track should be a video MediaStreamTrack\");await this._updateOriginMediaStreamTrack(e,t,!0),this.updateMediaStreamTrackResolution()}startMonitorStats(){if(!bg()&&!Og())return;this._statsTimer&&window.clearInterval(this._statsTimer);let e=2,t=NA[e];let i=-1;let n=Date.now();const r=e=>{e>2||e<0||(n=Date.now(),t=NA[e],this.setSenderConfiguration(t))};this.isUseScaleResolutionDownBy=!0,this._statsTimer=window.setInterval((()=>{const s=this.getStats(),o=AT(this,BA.GET_RTC_STATS);if(s.sendPackets>0&&o){-1===i&&(i=Date.now());const a=Date.now();if(a-i<1e3||a-n0&&c0&&(e--,r(e),jC.debug(\"[\".concat(this.getTrackId(),\"] step down for fps \").concat(c,\", switchProfile to \").concat(e))):o.OutgoingAvailableBandwidth0&&(e--,r(e),jC.debug(\"[\".concat(this.getTrackId(),\"] step down for OutgoingAvailableBandwidth \").concat(o.OutgoingAvailableBandwidth,\", bitrateMin \").concat(t.bitrateMin,\", switchProfile to \").concat(e))):\"number\"==typeof c&&c>l&&e1.2*NA[e+1].bitrateMin&&(e++,r(e),jC.debug(\"[\".concat(this.getTrackId(),\"] step up for fps \").concat(c,\", OutgoingAvailableBandwidth \").concat(o.OutgoingAvailableBandwidth,\", switchProfile to \").concat(e)))}}),RC(\"CHECK_LOCAL_STATS_INTERVAL\"))}sendSeiData(e){if(JT((()=>{eI.reportApiInvoke(null,{name:hT.LOCAL_VIDEO_SEND_SEI_DATA,options:[],tag:pT.TRACER}).onSuccess(\"\")}),this._mediaStreamTrack.id||this.getTrackId()),!RC(\"ENABLE_VIDEO_SEI\")||!RC(\"ENABLE_ENCODED_TRANSFORM\"))return void jC.warning('To send/receive SEI, please call AgoraRTC.setParameter(\"ENABLE_VIDEO_SEI\", true) before instantiate IAgoraRtcClient');if(e instanceof Uint8Array==!1)return new Kg(Hg.INVALID_PARAMS,\"Invalid argument type, ILocalVideoTrack.sendSeiData() only accept Uint8Array argument.\").throw();const t=this.getRTCRtpTransceiver();if(!t)return void jC.warning(\"Video track is not published, SEI can not be send\");const i=t.sender.getParameters();if(0===i.codecs.length)return;const n=i.codecs[0].mimeType.toLocaleLowerCase();\"video/h264\"===n?this.safeEmit(\"sei-to-send\",e):jC.warning(\"SEI is not supported by \".concat(n))}bindProcessorDestinationEvents(){this.processorDestination.on(tb.ON_TRACK,(async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(),await yT(this,BA.NEED_REPLACE_TRACK,this)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await yT(this,BA.NEED_REPLACE_TRACK,this))}))}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(tb.ON_TRACK)}unbindProcessorContextEvents(){this.processorContext.removeAllListeners(ib.REQUEST_UPDATE_CONSTRAINTS),this.processorContext.removeAllListeners(ib.REQUEST_CONSTRAINTS)}}DI([$C({argsMap:(e,t,i)=>[e.getTrackId(),\"string\"==typeof t?t:t instanceof HTMLVideoElement?\"HTMLVideoElement\":\"HTMLElement\",i]}),Wb(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[Object,Object]),PI(\"design:returntype\",void 0)],Rw.prototype,\"play\",null),DI([$C({argsMap:e=>[e.getTrackId()]}),PI(\"design:type\",Function),PI(\"design:paramtypes\",[]),PI(\"design:returntype\",void 0)],Rw.prototype,\"stop\",null),DI([_S(\"LocalVideoTrack\",\"_enabledMutex\"),$C({argsMap:(e,t)=>[e.getTrackId(),t]}),Wb(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[Boolean,Boolean]),PI(\"design:returntype\",cg)],Rw.prototype,\"setEnabled\",null),DI([_S(\"LocalVideoTrack\",\"_enabledMutex\"),$C({argsMap:(e,t)=>[e.getTrackId(),t]}),Wb(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[Boolean]),PI(\"design:returntype\",cg)],Rw.prototype,\"setMuted\",null),DI([$C({argsMap:(e,t)=>[e.getTrackId(),t]}),Wb(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[Object,Boolean]),PI(\"design:returntype\",cg)],Rw.prototype,\"setEncoderConfiguration\",null),DI([Wb(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[]),PI(\"design:returntype\",Object)],Rw.prototype,\"getStats\",null),DI([$C({argsMap:(e,t,i)=>[e.getTrackId(),t,i]}),Wb(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[Boolean,Object]),PI(\"design:returntype\",cg)],Rw.prototype,\"setBeautyEffect\",null),DI([Wb(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[]),PI(\"design:returntype\",ImageData)],Rw.prototype,\"getCurrentFrameData\",null),DI([Wb(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[String,Number]),PI(\"design:returntype\",cg)],Rw.prototype,\"getCurrentFrameImage\",null),DI([Wb(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[Object]),PI(\"design:returntype\",cg)],Rw.prototype,\"setBitrateLimit\",null),DI([Wb(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[String]),PI(\"design:returntype\",cg)],Rw.prototype,\"setOptimizationMode\",null),DI([Wb(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[Object]),PI(\"design:returntype\",void 0)],Rw.prototype,\"setScalabiltyMode\",null),DI([Wb(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[]),PI(\"design:returntype\",void 0)],Rw.prototype,\"updateMediaStreamTrackResolution\",null),DI([$C({argsMap:(e,t)=>[e.getTrackId(),t.name]}),PI(\"design:type\",Function),PI(\"design:paramtypes\",[Object]),PI(\"design:returntype\",Object)],Rw.prototype,\"pipe\",null),DI([$C({argsMap:e=>[e.getTrackId()]}),PI(\"design:type\",Function),PI(\"design:paramtypes\",[]),PI(\"design:returntype\",void 0)],Rw.prototype,\"unpipe\",null),DI([$C({argsMap:e=>[e.getTrackId()]}),PI(\"design:type\",Function),PI(\"design:paramtypes\",[]),PI(\"design:returntype\",void 0)],Rw.prototype,\"close\",null),DI([$C({argsMap:(e,t,i)=>[e.getTrackId(),t.label,i]}),PI(\"design:type\",Function),PI(\"design:paramtypes\",[MediaStreamTrack,Boolean]),PI(\"design:returntype\",cg)],Rw.prototype,\"replaceTrack\",null),DI([$C(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[]),PI(\"design:returntype\",void 0)],Rw.prototype,\"startMonitorStats\",null);class Cw extends Rw{get __className__(){return\"CameraVideoTrack\"}constructor(e,t,i,n,r,s){super(e,LA(t.encoderConfig),n,r,s),sh(this,\"_config\",void 0),sh(this,\"_originalConstraints\",void 0),sh(this,\"_constraints\",void 0),sh(this,\"_enabled\",!0),sh(this,\"_deviceName\",\"default\"),sh(this,\"tryResumeVideoForIOS15_16WeChat\",(async()=>{(Mg()||Ug())&&!function(){const e=Sg();if(e.os!==_g.IOS||!e.osVersion)return!1;const t=e.osVersion.split(\".\");return 15===Number(t[0])&&Number(t[1])>=2}()&&Fg()&&this._enabled&&!this._isClosed&&(jC.debug(\"[\".concat(this.getTrackId(),\"] try capture camera media device for interrupted iOS 15 device on WeChat.\")),await this.renewMediaStreamTrack())})),this._config=t,this._originalConstraints=i,this._constraints=i,this._deviceName=e.label,this._encoderConfig=LA(this._config.encoderConfig),_b.on(vA.IOS_15_16_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),_b.on(vA.IOS_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),this.bindProcessorContextEvents()}async setDevice(e){return\"string\"==typeof e?this._setDeviceById(e):e.deviceId?this._setDeviceById(e.deviceId):e.facingMode?this._setDeviceByFacingModel(e.facingMode):void 0}async _setDeviceById(e){if(jC.info(\"[\".concat(this.getTrackId(),\"] set device to \").concat(e)),this._enabled)try{const t=await kb.getDeviceById(e),i={};i.video=Sw({},this._constraints),i.video.deviceId={exact:e},i.video.facingMode=void 0,this._originMediaStreamTrack.stop();let n=null;try{n=await Nb(i,this.getTrackId())}catch(e){throw jC.error(\"[\".concat(this.getTrackId(),\"] setDevice failed\"),e.toString()),n=await Nb({video:this._constraints},this.getTrackId()),await this._updateOriginMediaStreamTrack(n.getVideoTracks()[0],!1),e}await this._updateOriginMediaStreamTrack(n.getVideoTracks()[0],!1),this.updateMediaStreamTrackResolution(),this._deviceName=t.label,this._config.cameraId=e,this._constraints.deviceId={exact:e}}catch(e){throw jC.error(\"[\".concat(this.getTrackId(),\"] setDevice error\"),e.toString()),e}else try{const t=await kb.getDeviceById(e);this._deviceName=t.label,this._config.cameraId=e,this._constraints.deviceId={exact:e}}catch(e){throw jC.error(\"[\".concat(this.getTrackId(),\"] setDevice error\"),e.toString()),e}jC.info(\"[\".concat(this.getTrackId(),\"] setDevice success\"))}async _setDeviceByFacingModel(e){jC.info(\"[\".concat(this.getTrackId(),\"] set facingMode \").concat(e));const t={video:Sw(Sw({},this._constraints),{},{deviceId:void 0,facingMode:{exact:e}})};if(this._enabled){this._originMediaStreamTrack.stop();let e=null;try{e=await Nb(t,this.getTrackId())}catch(t){throw jC.error(\"[\".concat(this.getTrackId(),\"] setDeviceByFacingModel failed\"),t.toString()),e=await Nb({video:this._constraints},this.getTrackId()),await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!1),t}await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!1),this.updateMediaStreamTrackResolution()}this._deviceName=\"\",this._config.facingMode=e,this._config.cameraId=void 0,this._constraints=Sw({},t.video),jC.info(\"[\".concat(this.getTrackId(),\"] setDeviceByFacingModel success\"))}async setEnabled(e,t){if(!t){if(e===this._enabled)return;this.stateCheck(\"enabled\",e)}if(jC.info(\"[\".concat(this.getTrackId(),\"] start setEnabled\"),e),e){try{if(this.isExternalTrack)this._originMediaStreamTrack.enabled=!0;else{const e=await Nb({video:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!1)}await yT(this,BA.NEED_ENABLE_TRACK,this)}catch(e){throw jC.error(\"[\".concat(this.getTrackId(),\"] setEnabled true error\"),e.toString()),e}this.updateMediaStreamTrackResolution(),jC.info(\"[\".concat(this.getTrackId(),\"] setEnabled to true success\")),t||(this._enabled=!0)}else{this.isExternalTrack?this._originMediaStreamTrack.enabled=!1:(this._originMediaStreamTrack.onended=null,this._originMediaStreamTrack.stop()),t||(this._enabled=!1);try{await yT(this,BA.NEED_DISABLE_TRACK,this)}catch(e){throw jC.error(\"[\".concat(this.getTrackId(),\"] setEnabled to false error\"),e.toString()),e}jC.info(\"[\".concat(this.getTrackId(),\"] setEnabled to false success\"))}}async setEncoderConfiguration(e,t){if(!this._enabled)throw new Kg(Hg.TRACK_IS_DISABLED,\"can not set encoder configuration when track is disabled\");\"720p_auto\"===e?this.startMonitorStats():this._statsTimer&&(window.clearInterval(this._statsTimer),this._statsTimer=null),e=LA(e),this._forceBitrateLimit&&(e.bitrateMax=this._forceBitrateLimit.max_bitrate?this._forceBitrateLimit.max_bitrate:e.bitrateMax,e.bitrateMin=this._forceBitrateLimit.min_bitrate?this._forceBitrateLimit.min_bitrate:e.bitrateMin);const i=YT(this._config);i.encoderConfig=e;const n=rw(i);(bg()||Og()||Vg())&&(n.deviceId=void 0),jC.debug(\"[\".concat(this.getTrackId(),\"] setEncoderConfiguration applyConstraints\"),JSON.stringify(e),JSON.stringify(n));try{await this._originMediaStreamTrack.applyConstraints(n),this.updateMediaStreamTrackResolution()}catch(e){const t=new Kg(Hg.UNEXPECTED_ERROR,e.toString());throw jC.error(\"[\".concat(this.getTrackId(),\"] applyConstraints error\"),t.toString()),t}this._config=i,this._constraints=n,this._originalConstraints=n,this._encoderConfig=e,-1===this._hints.indexOf(jA.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await yT(this,BA.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(jC)}}_getDefaultPlayerConfig(){return{mirror:!0,fit:\"cover\"}}onTrackEnded(){if((Og()||Vg())&&this._enabled&&!this._isClosed&&_b.duringInterruption){const e=async()=>{_b.off(vA.IOS_INTERRUPTION_END,e),this._enabled&&!this._isClosed&&(jC.debug(\"[\".concat(this.getTrackId(),\"] try capture camera media device for interrupted iOS device.\")),await this.setEnabled(!1),await this.setEnabled(!0))};_b.on(vA.IOS_INTERRUPTION_END,e)}else jC.debug(\"[\".concat(this.getTrackId(),\"] track ended\")),this.safeEmit(YA.TRACK_ENDED)}async renewMediaStreamTrack(e){const t=e||this._constraints,i=kb.searchDeviceIdByName(this._deviceName);if(i&&!t.deviceId&&(t.deviceId={exact:i}),this._enabled){const e=await Nb({video:t},this.getTrackId());this._constraints=t,await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!0),this.updateMediaStreamTrackResolution()}}close(){super.close(),_b.off(vA.IOS_15_16_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),_b.off(vA.IOS_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat)}clone(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],i=this._encoderConfig;e&&(i=Sw(Sw({},i),LA(e))),i=qT(i);const n=nS(8,\"track-cam-cloned-\"),r=new Cw(t?this._mediaStreamTrack.clone():this._mediaStreamTrack,qT(Sw(Sw({},this._config),{},{encoderConfig:i})),qT(this._constraints),qT(this._scalabilityMode),this._optimizationMode,n);return e&&i&&r.setEncoderConfiguration(i),jC.debug(\"clone track from \".concat(this.getTrackId(),\" to \").concat(n,\", clone \").concat(t)),r}bindProcessorContextEvents(){this.processorContext.on(ib.REQUEST_UPDATE_CONSTRAINTS,(async(e,t,i)=>{try{const i=Object.assign({},this._originalConstraints,...e);await this.renewMediaStreamTrack(i),t()}catch(e){i(e)}})),this.processorContext.on(ib.REQUEST_CONSTRAINTS,(async e=>{e(this._originMediaStreamTrack.getSettings())}))}}function Iw(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function vw(e){for(var t=1;t[e.getTrackId(),t]}),Wb(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[Object]),PI(\"design:returntype\",cg)],Cw.prototype,\"setDevice\",null),DI([_S(\"CameraVideoTrack\",\"_enabledMutex\"),$C({argsMap:(e,t)=>[e.getTrackId(),t]}),Wb(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[Boolean,Boolean]),PI(\"design:returntype\",cg)],Cw.prototype,\"setEnabled\",null),DI([$C({argsMap:(e,t)=>[e.getTrackId(),t]}),Wb(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[Object,Boolean]),PI(\"design:returntype\",cg)],Cw.prototype,\"setEncoderConfiguration\",null),DI([$C({argsMap:e=>[e.getTrackId()]}),PI(\"design:type\",Function),PI(\"design:paramtypes\",[]),PI(\"design:returntype\",void 0)],Cw.prototype,\"close\",null);class ww extends db{getUserId(){return this._userId}constructor(e,t,i,n){super(e,\"track-\".concat(e.kind,\"-\").concat(t,\"-\").concat(n.clientId,\"_\").concat(nS(5,\"\"))),sh(this,\"_userId\",void 0),sh(this,\"_uintId\",void 0),sh(this,\"_isDestroyed\",!1),sh(this,\"store\",void 0),sh(this,\"processor\",void 0),this._userId=t,this._uintId=i,this.store=n}_updateOriginMediaStreamTrack(e){this._originMediaStreamTrack=e,this._mediaStreamTrack=e,this._updatePlayerSource(),this.processor&&this.processor.updateInput({track:this._originMediaStreamTrack,context:this.processorContext})}_destroy(){this._isDestroyed=!0,jC.info(\"[\".concat(this.getTrackId(),\"] is destroyed\")),this.stop(),super.close()}getProcessorStats(){return this.processorContext.gatherStats()}getProcessorUsage(){return this.processorContext.gatherUsage()}}class Ow extends ww{get isPlaying(){return!(!this._player||this._player.videoElementStatus!==sb.PLAYING)}get __className__(){return\"RemoteVideoTrack\"}constructor(e,t,i,n){super(e,t,i,n),sh(this,\"_videoVisibleTimer\",null),sh(this,\"_previousVideoVisibleStatus\",void 0),sh(this,\"_clearPreviousVideoVisibleStatus\",(()=>this._previousVideoVisibleStatus=void 0)),sh(this,\"trackMediaType\",\"video\"),sh(this,\"_videoWidth\",void 0),sh(this,\"_videoHeight\",void 0),sh(this,\"_player\",void 0),sh(this,\"processorDestination\",void 0),sh(this,\"processorContext\",void 0),this.updateMediaStreamTrackResolution(),this.processorContext=new qb(this.getTrackId(),\"remote\"),this.processorDestination=new Yb(this.processorContext),this.bindProcessorDestinationEvents()}getStats(){JT((()=>{jC.warning(\"[deprecated] RemoteVideoTrack.getStats will be removed in the future, use AgoraRTCClient.getRemoteVideoStats instead\")}),\"remoteVideoTrackGetStatsWarning\");return AT(this,BA.GET_STATS)||bw({},eb)}play(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(\"string\"==typeof e){const t=document.getElementById(e);t?e=t:(jC.warning(\"[\".concat(this.getTrackId(),'] can not find \"#').concat(e,'\" element, use document.body')),e=document.body)}jC.debug(\"[\".concat(this.getTrackId(),\"] start video playback in \").concat(e instanceof HTMLVideoElement?\"HTMLVideoElement\":\"HTMLElement\"),JSON.stringify(t));const i=bw(bw({fit:\"cover\"},t),{},{trackId:this.getTrackId(),element:e});this._player?this._player.updateConfig(i):(e instanceof HTMLVideoElement?this._player=new pw(i):this._player=new Ew(i),this._player.updateVideoTrack(this._mediaStreamTrack),this._player.onFirstVideoFrameDecoded=()=>{this.store.subscribe(this.getUserId(),\"video\",void 0,void 0,Date.now()),this.safeEmit(qA.FIRST_FRAME_DECODED)},this._player.onVideoStateChanged=e=>{this.safeEmit(qA.VIDEO_STATE_CHANGED,e)}),this._player.play(this.store.sessionId||void 0),this._videoVisibleTimer&&window.clearInterval(this._videoVisibleTimer),this._clearPreviousVideoVisibleStatus(),this._videoVisibleTimer=window.setInterval((()=>{try{const e=this.getVideoElementVisibleStatus();this.safeEmit(qA.VIDEO_ELEMENT_VISIBLE_STATUS,e)}catch(e){}}),RC(\"CHECK_VIDEO_VISIBLE_INTERVAL\"))}stop(){this._player&&(this._videoVisibleTimer&&(window.clearInterval(this._videoVisibleTimer),this._videoVisibleTimer=null),this._clearPreviousVideoVisibleStatus(),this._player.destroy(),this._player=void 0,jC.debug(\"[\".concat(this.getTrackId(),\"] stop video playback\")))}getCurrentFrameData(){return this._player?this._player.getCurrentFrame():new ImageData(2,2)}updateMediaStreamTrackResolution(){mw(this._originMediaStreamTrack).then((e=>{let[t,i]=e;this._videoHeight=i,this._videoWidth=t})).catch(sS)}_updatePlayerSource(){jC.debug(\"[\".concat(this.getTrackId(),\"] update player source track\")),this._player&&this._player.updateVideoTrack(this._mediaStreamTrack)}getVideoElementVisibleStatus(){try{var e,t;const i=null==this||null===(e=this._player)||void 0===e?void 0:e.getContainerElement(),n={track:this,element:null==this||null===(t=this._player)||void 0===t?void 0:t.getVideoElement(),slot:null==i?void 0:i.parentElement},{element:r,slot:s}=n;if(this.isPlaying&&r instanceof HTMLVideoElement&&s instanceof HTMLElement){const e=rT.checkOneElementVisible(r),t=Object.assign({},e);if(t.visible!==this._previousVideoVisibleStatus){this._previousVideoVisibleStatus=t.visible;const e=eI.reportApiInvoke(null,{tag:pT.TRACER,name:hT.REMOTE_VIDEO_TRACK_GET_VIDEO_VISIBLE,options:[this.getTrackId()]});t.visible?e.onSuccess(\"Video is visible\"):e.onSuccess(\"Invisible because of \".concat(t.reason))}return t}return}catch(e){throw new Kg(Hg.GET_VIDEO_ELEMENT_VISIBLE_ERROR,e.message)}}pipe(e){if(this.processor===e)return e;if(e._source)throw new Kg(Hg.INVALID_OPERATION,\"Processor \".concat(e.name,\" already piped, please call unpipe beforehand.\"));return this.unpipe(),this.processor=e,this.processor._source=this,e.updateInput({track:this._originMediaStreamTrack,context:this.processorContext}),e}unpipe(){if(!this.processor)return;const e=this.processor;this.processor._source=void 0,this.processor=void 0,e.reset()}bindProcessorDestinationEvents(){this.processorDestination.on(tb.ON_TRACK,(async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource()):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource())}))}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(tb.ON_TRACK)}_destroy(){super._destroy(),this.unbindProcessorDestinationEvents()}_onSei(e){this.emit(KA.SEI_RECEIVED,e)}}DI([$C({argsMap:(e,t,i)=>[e.getTrackId(),\"string\"==typeof t?t:t instanceof HTMLVideoElement?\"HTMLVideoElement\":\"HTMLElement\",i]}),PI(\"design:type\",Function),PI(\"design:paramtypes\",[Object,Object]),PI(\"design:returntype\",void 0)],Ow.prototype,\"play\",null),DI([$C({argsMap:e=>[e.getTrackId()]}),PI(\"design:type\",Function),PI(\"design:paramtypes\",[]),PI(\"design:returntype\",void 0)],Ow.prototype,\"stop\",null),DI([$C({argsMap:(e,t)=>[e.getTrackId(),t.name]}),PI(\"design:type\",Function),PI(\"design:paramtypes\",[Object]),PI(\"design:returntype\",Object)],Ow.prototype,\"pipe\",null),DI([$C({argsMap:e=>[e.getTrackId()]}),PI(\"design:type\",Function),PI(\"design:paramtypes\",[]),PI(\"design:returntype\",void 0)],Ow.prototype,\"unpipe\",null);class Nw extends ww{get isPlaying(){return this._useAudioElement?Gb.isPlaying(this.getTrackId()):this._source.isPlayed}get __className__(){return\"RemoteAudioTrack\"}constructor(e,t,i,n){super(e,t,i,n),sh(this,\"trackMediaType\",\"audio\"),sh(this,\"_source\",void 0),sh(this,\"_useAudioElement\",!0),sh(this,\"_volume\",100),sh(this,\"processorContext\",void 0),sh(this,\"processorDestination\",void 0),sh(this,\"_played\",!1),sh(this,\"_bypassWebAudio\",!1),RC(\"DISABLE_WEBAUDIO\")?(this._source=new Xb,this._bypassWebAudio=!0,this._useAudioElement=!0):(this._source=new Cb(e,!0),RC(\"REMOTE_AUDIO_TRACK_USES_WEB_AUDIO\")&&(this._useAudioElement=!1)),this._source.once(zA.RECEIVE_TRACK_BUFFER,(()=>{this.safeEmit(qA.FIRST_FRAME_DECODED)})),this.processorContext=new Jb(this._source.context,this.getTrackId(),\"remote\"),this.processorDestination=new zb(this.processorContext),this.bindProcessorDestinationEvents(),this._source.on(zA.UPDATE_SOURCE,(()=>{this.processor&&this.processor.updateInput({node:this._source.processSourceNode,context:this.processorContext})}))}setAudioFrameCallback(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:4096;if(!e)return this._source.removeAllListeners(zA.ON_AUDIO_BUFFER),void this._source.stopGetAudioBuffer();this._source.startGetAudioBuffer(t),this._source.removeAllListeners(zA.ON_AUDIO_BUFFER),this._source.on(zA.ON_AUDIO_BUFFER,(t=>e(t)))}setVolume(e){this._volume=e,this._useAudioElement?Gb.setVolume(this.getTrackId(),e):this._source.setVolume(e/100)}async setPlaybackDevice(e){if(!this._useAudioElement||!Ag()&&RC(\"RESTRICTION_SET_PLAYBACK_DEVICE\"))throw new Kg(Hg.NOT_SUPPORTED,\"your browser does not support setting the audio output device\");await Gb.setSinkID(this.getTrackId(),e)}getVolumeLevel(){return this._source.getAccurateVolumeLevel()}getStats(){JT((()=>{jC.warning(\"[deprecated] RemoteAudioTrack.getStats will be removed in the future, use AgoraRTCClient.getRemoteAudioStats instead\")}),\"remoteAudioTrackGetStatsWarning\");return AT(this,BA.GET_STATS)||bw({},ZA)}play(){jC.debug(\"[\".concat(this.getTrackId(),\"] start audio playback\")),this._played=!0,this._useAudioElement?(jC.debug(\"[\".concat(this.getTrackId(),\"] use audio element to play\")),Gb.play(this._mediaStreamTrack,this.getTrackId(),this._volume,this.store.sessionId||void 0)):this._source.play()}stop(){jC.debug(\"[\".concat(this.getTrackId(),\"] stop audio playback\")),this._played=!1,this._useAudioElement?Gb.stop(this.getTrackId()):this._source.stop()}_destroy(){super._destroy(),this._played=!1,this.unbindProcessorDestinationEvents(),this._source.destroy()}_isFreeze(){return this._source.isFreeze}_updatePlayerSource(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];jC.debug(\"[\".concat(this.getTrackId(),\"] update player source track\")),e&&this._source.updateTrack(this._mediaStreamTrack),this._useAudioElement&&Gb.updateTrack(this.getTrackId(),this._mediaStreamTrack)}pipe(e){if(this._bypassWebAudio)throw new Kg(Hg.NOT_SUPPORTED,\"can not pipe extension when WebAudio disabled\");if(this.processor===e)return e;if(e._source)throw new Kg(Hg.INVALID_OPERATION,\"Processor \".concat(e.name,\" already piped, please call unpipe beforehand.\"));return this.unpipe(),this.processor=e,this.processor._source=this,e.updateInput({track:this._originMediaStreamTrack,node:this._source.processSourceNode,context:this.processorContext}),e}unpipe(){var e;if(this._bypassWebAudio)throw new Kg(Hg.NOT_SUPPORTED,\"can not unpipe extension when WebAudio disabled\");if(!this.processor)return;const t=this.processor;null===(e=this._source.processSourceNode)||void 0===e||e.disconnect(),this.processor._source=!1,this.processor=void 0,t.reset()}bindProcessorDestinationEvents(){this.processorDestination.on(tb.ON_TRACK,(async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(!1),this._source.processedNode=this._source.createMediaStreamSourceNode(e)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource())})),this.processorDestination.on(tb.ON_NODE,(e=>{this._source.processedNode=e;const t=!e;this._useAudioElement!==t&&(this._played?(this.stop(),this._useAudioElement=t,this.play()):this._useAudioElement=t)}))}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(tb.ON_TRACK),this.processorDestination.removeAllListeners(tb.ON_NODE)}}DI([$C({argsMap:(e,t)=>[e.getTrackId(),t],throttleTime:300}),PI(\"design:type\",Function),PI(\"design:paramtypes\",[Number]),PI(\"design:returntype\",void 0)],Nw.prototype,\"setVolume\",null),DI([$C({argsMap:(e,t)=>[e.getTrackId(),t]}),PI(\"design:type\",Function),PI(\"design:paramtypes\",[String]),PI(\"design:returntype\",cg)],Nw.prototype,\"setPlaybackDevice\",null),DI([$C({argsMap:e=>[e.getTrackId()]}),PI(\"design:type\",Function),PI(\"design:paramtypes\",[]),PI(\"design:returntype\",void 0)],Nw.prototype,\"play\",null),DI([$C({argsMap:e=>[e.getTrackId()]}),PI(\"design:type\",Function),PI(\"design:paramtypes\",[]),PI(\"design:returntype\",void 0)],Nw.prototype,\"stop\",null),DI([$C({argsMap:(e,t)=>[e.getTrackId(),t.name]}),PI(\"design:type\",Function),PI(\"design:paramtypes\",[Object]),PI(\"design:returntype\",Object)],Nw.prototype,\"pipe\",null),DI([$C({argsMap:e=>[e.getTrackId()]}),PI(\"design:type\",Function),PI(\"design:paramtypes\",[]),PI(\"design:returntype\",void 0)],Nw.prototype,\"unpipe\",null);const Dw=new class extends dT{get visibility(){return document.visibilityState}get lastHiddenTime(){return this._lastHiddenTime}get lastVisibleTime(){return this._lastVisibleTime}constructor(){super(),sh(this,\"_lastHiddenTime\",0),sh(this,\"_lastVisibleTime\",0),document.addEventListener(\"visibilitychange\",(()=>{\"hidden\"===document.visibilityState?this._lastHiddenTime=performance.now():this._lastVisibleTime=performance.now(),jC.debug(\"document visibility went \".concat(document.visibilityState)),this.emit(\"VISIBILITY_CHANGE\",document.visibilityState)}))}};\n/*! pako 2.1.0 https://github.com/nodeca/pako @license (MIT AND Zlib) */function Pw(e){let t=e.length;for(;--t>=0;)e[t]=0}const Lw=256,kw=286,Mw=30,Uw=15,xw=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]),Vw=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]),Fw=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),Bw=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),jw=new Array(576);Pw(jw);const Gw=new Array(60);Pw(Gw);const Ww=new Array(512);Pw(Ww);const Hw=new Array(256);Pw(Hw);const Kw=new Array(29);Pw(Kw);const Yw=new Array(Mw);function qw(e,t,i,n,r){this.static_tree=e,this.extra_bits=t,this.extra_base=i,this.elems=n,this.max_length=r,this.has_stree=e&&e.length}let zw,Jw,Xw;function Qw(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}Pw(Yw);const Zw=e=>e<256?Ww[e]:Ww[256+(e>>>7)],$w=(e,t)=>{e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255},eO=(e,t,i)=>{e.bi_valid>16-i?(e.bi_buf|=t<>16-e.bi_valid,e.bi_valid+=i-16):(e.bi_buf|=t<{eO(e,i[2*t],i[2*t+1])},iO=(e,t)=>{let i=0;do{i|=1&e,e>>>=1,i<<=1}while(--t>0);return i>>>1},nO=(e,t,i)=>{const n=new Array(16);let r,s,o=0;for(r=1;r<=Uw;r++)o=o+i[r-1]<<1,n[r]=o;for(s=0;s<=t;s++){let t=e[2*s+1];0!==t&&(e[2*s]=iO(n[t]++,t))}},rO=e=>{let t;for(t=0;t{e.bi_valid>8?$w(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0},oO=(e,t,i,n)=>{const r=2*t,s=2*i;return e[r]{const n=e.heap[i];let r=i<<1;for(;r<=e.heap_len&&(r{let n,r,s,o,a=0;if(0!==e.sym_next)do{n=255&e.pending_buf[e.sym_buf+a++],n+=(255&e.pending_buf[e.sym_buf+a++])<<8,r=e.pending_buf[e.sym_buf+a++],0===n?tO(e,r,t):(s=Hw[r],tO(e,s+Lw+1,t),o=xw[s],0!==o&&(r-=Kw[s],eO(e,r,o)),n--,s=Zw(n),tO(e,s,i),o=Vw[s],0!==o&&(n-=Yw[s],eO(e,n,o)))}while(a{const i=t.dyn_tree,n=t.stat_desc.static_tree,r=t.stat_desc.has_stree,s=t.stat_desc.elems;let o,a,c,d=-1;for(e.heap_len=0,e.heap_max=573,o=0;o>1;o>=1;o--)aO(e,i,o);c=s;do{o=e.heap[1],e.heap[1]=e.heap[e.heap_len--],aO(e,i,1),a=e.heap[1],e.heap[--e.heap_max]=o,e.heap[--e.heap_max]=a,i[2*c]=i[2*o]+i[2*a],e.depth[c]=(e.depth[o]>=e.depth[a]?e.depth[o]:e.depth[a])+1,i[2*o+1]=i[2*a+1]=c,e.heap[1]=c++,aO(e,i,1)}while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],((e,t)=>{const i=t.dyn_tree,n=t.max_code,r=t.stat_desc.static_tree,s=t.stat_desc.has_stree,o=t.stat_desc.extra_bits,a=t.stat_desc.extra_base,c=t.stat_desc.max_length;let d,l,u,h,p,_,E=0;for(h=0;h<=Uw;h++)e.bl_count[h]=0;for(i[2*e.heap[e.heap_max]+1]=0,d=e.heap_max+1;d<573;d++)l=e.heap[d],h=i[2*i[2*l+1]+1]+1,h>c&&(h=c,E++),i[2*l+1]=h,l>n||(e.bl_count[h]++,p=0,l>=a&&(p=o[l-a]),_=i[2*l],e.opt_len+=_*(h+p),s&&(e.static_len+=_*(r[2*l+1]+p)));if(0!==E){do{for(h=c-1;0===e.bl_count[h];)h--;e.bl_count[h]--,e.bl_count[h+1]+=2,e.bl_count[c]--,E-=2}while(E>0);for(h=c;0!==h;h--)for(l=e.bl_count[h];0!==l;)u=e.heap[--d],u>n||(i[2*u+1]!==h&&(e.opt_len+=(h-i[2*u+1])*i[2*u],i[2*u+1]=h),l--)}})(e,t),nO(i,d,e.bl_count)},lO=(e,t,i)=>{let n,r,s=-1,o=t[1],a=0,c=7,d=4;for(0===o&&(c=138,d=3),t[2*(i+1)+1]=65535,n=0;n<=i;n++)r=o,o=t[2*(n+1)+1],++a{let n,r,s=-1,o=t[1],a=0,c=7,d=4;for(0===o&&(c=138,d=3),n=0;n<=i;n++)if(r=o,o=t[2*(n+1)+1],!(++a{eO(e,0+(n?1:0),3),sO(e),$w(e,i),$w(e,~i),i&&e.pending_buf.set(e.window.subarray(t,t+i),e.pending),e.pending+=i};var _O=e=>{hO||((()=>{let e,t,i,n,r;const s=new Array(16);for(i=0,n=0;n<28;n++)for(Kw[n]=i,e=0;e<1<>=7;n{let r,s,o=0;e.level>0?(2===e.strm.data_type&&(e.strm.data_type=(e=>{let t,i=4093624447;for(t=0;t<=31;t++,i>>>=1)if(1&i&&0!==e.dyn_ltree[2*t])return 0;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return 1;for(t=32;t{let t;for(lO(e,e.dyn_ltree,e.l_desc.max_code),lO(e,e.dyn_dtree,e.d_desc.max_code),dO(e,e.bl_desc),t=18;t>=3&&0===e.bl_tree[2*Bw[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t})(e),r=e.opt_len+3+7>>>3,s=e.static_len+3+7>>>3,s<=r&&(r=s)):r=s=i+5,i+4<=r&&-1!==t?pO(e,t,i,n):4===e.strategy||s===r?(eO(e,2+(n?1:0),3),cO(e,jw,Gw)):(eO(e,4+(n?1:0),3),((e,t,i,n)=>{let r;for(eO(e,t-257,5),eO(e,i-1,5),eO(e,n-4,4),r=0;r(e.pending_buf[e.sym_buf+e.sym_next++]=t,e.pending_buf[e.sym_buf+e.sym_next++]=t>>8,e.pending_buf[e.sym_buf+e.sym_next++]=i,0===t?e.dyn_ltree[2*i]++:(e.matches++,t--,e.dyn_ltree[2*(Hw[i]+Lw+1)]++,e.dyn_dtree[2*Zw(t)]++),e.sym_next===e.sym_end),fO={_tr_init:_O,_tr_stored_block:pO,_tr_flush_block:EO,_tr_tally:mO,_tr_align:e=>{eO(e,2,3),tO(e,256,jw),(e=>{16===e.bi_valid?($w(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8)})(e)}};var gO=(e,t,i,n)=>{let r=65535&e|0,s=e>>>16&65535|0,o=0;for(;0!==i;){o=i>2e3?2e3:i,i-=o;do{r=r+t[n++]|0,s=s+r|0}while(--o);r%=65521,s%=65521}return r|s<<16|0};const TO=new Uint32Array((()=>{let e,t=[];for(var i=0;i<256;i++){e=i;for(var n=0;n<8;n++)e=1&e?3988292384^e>>>1:e>>>1;t[i]=e}return t})());var SO=(e,t,i,n)=>{const r=TO,s=n+i;e^=-1;for(let i=n;i>>8^r[255&(e^t[i])];return-1^e},RO={2:\"need dictionary\",1:\"stream end\",0:\"\",\"-1\":\"file error\",\"-2\":\"stream error\",\"-3\":\"data error\",\"-4\":\"insufficient memory\",\"-5\":\"buffer error\",\"-6\":\"incompatible version\"},CO={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8};const{_tr_init:IO,_tr_stored_block:vO,_tr_flush_block:yO,_tr_tally:AO,_tr_align:bO}=fO,{Z_NO_FLUSH:wO,Z_PARTIAL_FLUSH:OO,Z_FULL_FLUSH:NO,Z_FINISH:DO,Z_BLOCK:PO,Z_OK:LO,Z_STREAM_END:kO,Z_STREAM_ERROR:MO,Z_DATA_ERROR:UO,Z_BUF_ERROR:xO,Z_DEFAULT_COMPRESSION:VO,Z_FILTERED:FO,Z_HUFFMAN_ONLY:BO,Z_RLE:jO,Z_FIXED:GO,Z_DEFAULT_STRATEGY:WO,Z_UNKNOWN:HO,Z_DEFLATED:KO}=CO,YO=286,qO=30,zO=19,JO=2*YO+1,XO=15,QO=258,ZO=262,$O=42,eN=113,tN=666,iN=(e,t)=>(e.msg=RO[t],t),nN=e=>2*e-(e>4?9:0),rN=e=>{let t=e.length;for(;--t>=0;)e[t]=0},sN=e=>{let t,i,n,r=e.w_size;t=e.hash_size,n=t;do{i=e.head[--n],e.head[n]=i>=r?i-r:0}while(--t);t=r,n=t;do{i=e.prev[--n],e.prev[n]=i>=r?i-r:0}while(--t)};let oN=(e,t,i)=>(t<{const t=e.state;let i=t.pending;i>e.avail_out&&(i=e.avail_out),0!==i&&(e.output.set(t.pending_buf.subarray(t.pending_out,t.pending_out+i),e.next_out),e.next_out+=i,t.pending_out+=i,e.total_out+=i,e.avail_out-=i,t.pending-=i,0===t.pending&&(t.pending_out=0))},cN=(e,t)=>{yO(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,aN(e.strm)},dN=(e,t)=>{e.pending_buf[e.pending++]=t},lN=(e,t)=>{e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t},uN=(e,t,i,n)=>{let r=e.avail_in;return r>n&&(r=n),0===r?0:(e.avail_in-=r,t.set(e.input.subarray(e.next_in,e.next_in+r),i),1===e.state.wrap?e.adler=gO(e.adler,t,r,i):2===e.state.wrap&&(e.adler=SO(e.adler,t,r,i)),e.next_in+=r,e.total_in+=r,r)},hN=(e,t)=>{let i,n,r=e.max_chain_length,s=e.strstart,o=e.prev_length,a=e.nice_match;const c=e.strstart>e.w_size-ZO?e.strstart-(e.w_size-ZO):0,d=e.window,l=e.w_mask,u=e.prev,h=e.strstart+QO;let p=d[s+o-1],_=d[s+o];e.prev_length>=e.good_match&&(r>>=2),a>e.lookahead&&(a=e.lookahead);do{if(i=t,d[i+o]===_&&d[i+o-1]===p&&d[i]===d[s]&&d[++i]===d[s+1]){s+=2,i++;do{}while(d[++s]===d[++i]&&d[++s]===d[++i]&&d[++s]===d[++i]&&d[++s]===d[++i]&&d[++s]===d[++i]&&d[++s]===d[++i]&&d[++s]===d[++i]&&d[++s]===d[++i]&&so){if(e.match_start=t,o=n,n>=a)break;p=d[s+o-1],_=d[s+o]}}}while((t=u[t&l])>c&&0!=--r);return o<=e.lookahead?o:e.lookahead},pN=e=>{const t=e.w_size;let i,n,r;do{if(n=e.window_size-e.lookahead-e.strstart,e.strstart>=t+(t-ZO)&&(e.window.set(e.window.subarray(t,t+t-n),0),e.match_start-=t,e.strstart-=t,e.block_start-=t,e.insert>e.strstart&&(e.insert=e.strstart),sN(e),n+=t),0===e.strm.avail_in)break;if(i=uN(e.strm,e.window,e.strstart+e.lookahead,n),e.lookahead+=i,e.lookahead+e.insert>=3)for(r=e.strstart-e.insert,e.ins_h=e.window[r],e.ins_h=oN(e,e.ins_h,e.window[r+1]);e.insert&&(e.ins_h=oN(e,e.ins_h,e.window[r+3-1]),e.prev[r&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=r,r++,e.insert--,!(e.lookahead+e.insert<3)););}while(e.lookahead{let i,n,r,s=e.pending_buf_size-5>e.w_size?e.w_size:e.pending_buf_size-5,o=0,a=e.strm.avail_in;do{if(i=65535,r=e.bi_valid+42>>3,e.strm.avail_outn+e.strm.avail_in&&(i=n+e.strm.avail_in),i>r&&(i=r),i>8,e.pending_buf[e.pending-2]=~i,e.pending_buf[e.pending-1]=~i>>8,aN(e.strm),n&&(n>i&&(n=i),e.strm.output.set(e.window.subarray(e.block_start,e.block_start+n),e.strm.next_out),e.strm.next_out+=n,e.strm.avail_out-=n,e.strm.total_out+=n,e.block_start+=n,i-=n),i&&(uN(e.strm,e.strm.output,e.strm.next_out,i),e.strm.next_out+=i,e.strm.avail_out-=i,e.strm.total_out+=i)}while(0===o);return a-=e.strm.avail_in,a&&(a>=e.w_size?(e.matches=2,e.window.set(e.strm.input.subarray(e.strm.next_in-e.w_size,e.strm.next_in),0),e.strstart=e.w_size,e.insert=e.strstart):(e.window_size-e.strstart<=a&&(e.strstart-=e.w_size,e.window.set(e.window.subarray(e.w_size,e.w_size+e.strstart),0),e.matches<2&&e.matches++,e.insert>e.strstart&&(e.insert=e.strstart)),e.window.set(e.strm.input.subarray(e.strm.next_in-a,e.strm.next_in),e.strstart),e.strstart+=a,e.insert+=a>e.w_size-e.insert?e.w_size-e.insert:a),e.block_start=e.strstart),e.high_waterr&&e.block_start>=e.w_size&&(e.block_start-=e.w_size,e.strstart-=e.w_size,e.window.set(e.window.subarray(e.w_size,e.w_size+e.strstart),0),e.matches<2&&e.matches++,r+=e.w_size,e.insert>e.strstart&&(e.insert=e.strstart)),r>e.strm.avail_in&&(r=e.strm.avail_in),r&&(uN(e.strm,e.window,e.strstart,r),e.strstart+=r,e.insert+=r>e.w_size-e.insert?e.w_size-e.insert:r),e.high_water>3,r=e.pending_buf_size-r>65535?65535:e.pending_buf_size-r,s=r>e.w_size?e.w_size:r,n=e.strstart-e.block_start,(n>=s||(n||t===DO)&&t!==wO&&0===e.strm.avail_in&&n<=r)&&(i=n>r?r:n,o=t===DO&&0===e.strm.avail_in&&i===n?1:0,vO(e,e.block_start,i,o),e.block_start+=i,aN(e.strm)),o?3:1)},EN=(e,t)=>{let i,n;for(;;){if(e.lookahead=3&&(e.ins_h=oN(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),0!==i&&e.strstart-i<=e.w_size-ZO&&(e.match_length=hN(e,i)),e.match_length>=3)if(n=AO(e,e.strstart-e.match_start,e.match_length-3),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=3){e.match_length--;do{e.strstart++,e.ins_h=oN(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart}while(0!=--e.match_length);e.strstart++}else e.strstart+=e.match_length,e.match_length=0,e.ins_h=e.window[e.strstart],e.ins_h=oN(e,e.ins_h,e.window[e.strstart+1]);else n=AO(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(n&&(cN(e,!1),0===e.strm.avail_out))return 1}return e.insert=e.strstart<2?e.strstart:2,t===DO?(cN(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(cN(e,!1),0===e.strm.avail_out)?1:2},mN=(e,t)=>{let i,n,r;for(;;){if(e.lookahead=3&&(e.ins_h=oN(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),e.prev_length=e.match_length,e.prev_match=e.match_start,e.match_length=2,0!==i&&e.prev_length4096)&&(e.match_length=2)),e.prev_length>=3&&e.match_length<=e.prev_length){r=e.strstart+e.lookahead-3,n=AO(e,e.strstart-1-e.prev_match,e.prev_length-3),e.lookahead-=e.prev_length-1,e.prev_length-=2;do{++e.strstart<=r&&(e.ins_h=oN(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart)}while(0!=--e.prev_length);if(e.match_available=0,e.match_length=2,e.strstart++,n&&(cN(e,!1),0===e.strm.avail_out))return 1}else if(e.match_available){if(n=AO(e,0,e.window[e.strstart-1]),n&&cN(e,!1),e.strstart++,e.lookahead--,0===e.strm.avail_out)return 1}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&(n=AO(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<2?e.strstart:2,t===DO?(cN(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(cN(e,!1),0===e.strm.avail_out)?1:2};function fN(e,t,i,n,r){this.good_length=e,this.max_lazy=t,this.nice_length=i,this.max_chain=n,this.func=r}const gN=[new fN(0,0,0,0,_N),new fN(4,4,8,4,EN),new fN(4,5,16,8,EN),new fN(4,6,32,32,EN),new fN(4,4,16,16,mN),new fN(8,16,32,32,mN),new fN(8,16,128,128,mN),new fN(8,32,128,256,mN),new fN(32,128,258,1024,mN),new fN(32,258,258,4096,mN)];function TN(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=KO,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(2*JO),this.dyn_dtree=new Uint16Array(2*(2*qO+1)),this.bl_tree=new Uint16Array(2*(2*zO+1)),rN(this.dyn_ltree),rN(this.dyn_dtree),rN(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(XO+1),this.heap=new Uint16Array(2*YO+1),rN(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(2*YO+1),rN(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}const SN=e=>{if(!e)return 1;const t=e.state;return!t||t.strm!==e||t.status!==$O&&57!==t.status&&69!==t.status&&73!==t.status&&91!==t.status&&103!==t.status&&t.status!==eN&&t.status!==tN?1:0},RN=e=>{if(SN(e))return iN(e,MO);e.total_in=e.total_out=0,e.data_type=HO;const t=e.state;return t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=2===t.wrap?57:t.wrap?$O:eN,e.adler=2===t.wrap?0:1,t.last_flush=-2,IO(t),LO},CN=e=>{const t=RN(e);var i;return t===LO&&((i=e.state).window_size=2*i.w_size,rN(i.head),i.max_lazy_match=gN[i.level].max_lazy,i.good_match=gN[i.level].good_length,i.nice_match=gN[i.level].nice_length,i.max_chain_length=gN[i.level].max_chain,i.strstart=0,i.block_start=0,i.lookahead=0,i.insert=0,i.match_length=i.prev_length=2,i.match_available=0,i.ins_h=0),t},IN=(e,t,i,n,r,s)=>{if(!e)return MO;let o=1;if(t===VO&&(t=6),n<0?(o=0,n=-n):n>15&&(o=2,n-=16),r<1||r>9||i!==KO||n<8||n>15||t<0||t>9||s<0||s>GO||8===n&&1!==o)return iN(e,MO);8===n&&(n=9);const a=new TN;return e.state=a,a.strm=e,a.status=$O,a.wrap=o,a.gzhead=null,a.w_bits=n,a.w_size=1<{if(SN(e)||t>PO||t<0)return e?iN(e,MO):MO;const i=e.state;if(!e.output||0!==e.avail_in&&!e.input||i.status===tN&&t!==DO)return iN(e,0===e.avail_out?xO:MO);const n=i.last_flush;if(i.last_flush=t,0!==i.pending){if(aN(e),0===e.avail_out)return i.last_flush=-1,LO}else if(0===e.avail_in&&nN(t)<=nN(n)&&t!==DO)return iN(e,xO);if(i.status===tN&&0!==e.avail_in)return iN(e,xO);if(i.status===$O&&0===i.wrap&&(i.status=eN),i.status===$O){let t=KO+(i.w_bits-8<<4)<<8,n=-1;if(n=i.strategy>=BO||i.level<2?0:i.level<6?1:6===i.level?2:3,t|=n<<6,0!==i.strstart&&(t|=32),t+=31-t%31,lN(i,t),0!==i.strstart&&(lN(i,e.adler>>>16),lN(i,65535&e.adler)),e.adler=1,i.status=eN,aN(e),0!==i.pending)return i.last_flush=-1,LO}if(57===i.status)if(e.adler=0,dN(i,31),dN(i,139),dN(i,8),i.gzhead)dN(i,(i.gzhead.text?1:0)+(i.gzhead.hcrc?2:0)+(i.gzhead.extra?4:0)+(i.gzhead.name?8:0)+(i.gzhead.comment?16:0)),dN(i,255&i.gzhead.time),dN(i,i.gzhead.time>>8&255),dN(i,i.gzhead.time>>16&255),dN(i,i.gzhead.time>>24&255),dN(i,9===i.level?2:i.strategy>=BO||i.level<2?4:0),dN(i,255&i.gzhead.os),i.gzhead.extra&&i.gzhead.extra.length&&(dN(i,255&i.gzhead.extra.length),dN(i,i.gzhead.extra.length>>8&255)),i.gzhead.hcrc&&(e.adler=SO(e.adler,i.pending_buf,i.pending,0)),i.gzindex=0,i.status=69;else if(dN(i,0),dN(i,0),dN(i,0),dN(i,0),dN(i,0),dN(i,9===i.level?2:i.strategy>=BO||i.level<2?4:0),dN(i,3),i.status=eN,aN(e),0!==i.pending)return i.last_flush=-1,LO;if(69===i.status){if(i.gzhead.extra){let t=i.pending,n=(65535&i.gzhead.extra.length)-i.gzindex;for(;i.pending+n>i.pending_buf_size;){let r=i.pending_buf_size-i.pending;if(i.pending_buf.set(i.gzhead.extra.subarray(i.gzindex,i.gzindex+r),i.pending),i.pending=i.pending_buf_size,i.gzhead.hcrc&&i.pending>t&&(e.adler=SO(e.adler,i.pending_buf,i.pending-t,t)),i.gzindex+=r,aN(e),0!==i.pending)return i.last_flush=-1,LO;t=0,n-=r}let r=new Uint8Array(i.gzhead.extra);i.pending_buf.set(r.subarray(i.gzindex,i.gzindex+n),i.pending),i.pending+=n,i.gzhead.hcrc&&i.pending>t&&(e.adler=SO(e.adler,i.pending_buf,i.pending-t,t)),i.gzindex=0}i.status=73}if(73===i.status){if(i.gzhead.name){let t,n=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>n&&(e.adler=SO(e.adler,i.pending_buf,i.pending-n,n)),aN(e),0!==i.pending)return i.last_flush=-1,LO;n=0}t=i.gzindexn&&(e.adler=SO(e.adler,i.pending_buf,i.pending-n,n)),i.gzindex=0}i.status=91}if(91===i.status){if(i.gzhead.comment){let t,n=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>n&&(e.adler=SO(e.adler,i.pending_buf,i.pending-n,n)),aN(e),0!==i.pending)return i.last_flush=-1,LO;n=0}t=i.gzindexn&&(e.adler=SO(e.adler,i.pending_buf,i.pending-n,n))}i.status=103}if(103===i.status){if(i.gzhead.hcrc){if(i.pending+2>i.pending_buf_size&&(aN(e),0!==i.pending))return i.last_flush=-1,LO;dN(i,255&e.adler),dN(i,e.adler>>8&255),e.adler=0}if(i.status=eN,aN(e),0!==i.pending)return i.last_flush=-1,LO}if(0!==e.avail_in||0!==i.lookahead||t!==wO&&i.status!==tN){let n=0===i.level?_N(i,t):i.strategy===BO?((e,t)=>{let i;for(;;){if(0===e.lookahead&&(pN(e),0===e.lookahead)){if(t===wO)return 1;break}if(e.match_length=0,i=AO(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,i&&(cN(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===DO?(cN(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(cN(e,!1),0===e.strm.avail_out)?1:2})(i,t):i.strategy===jO?((e,t)=>{let i,n,r,s;const o=e.window;for(;;){if(e.lookahead<=QO){if(pN(e),e.lookahead<=QO&&t===wO)return 1;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=3&&e.strstart>0&&(r=e.strstart-1,n=o[r],n===o[++r]&&n===o[++r]&&n===o[++r])){s=e.strstart+QO;do{}while(n===o[++r]&&n===o[++r]&&n===o[++r]&&n===o[++r]&&n===o[++r]&&n===o[++r]&&n===o[++r]&&n===o[++r]&&re.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=3?(i=AO(e,1,e.match_length-3),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(i=AO(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),i&&(cN(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===DO?(cN(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(cN(e,!1),0===e.strm.avail_out)?1:2})(i,t):gN[i.level].func(i,t);if(3!==n&&4!==n||(i.status=tN),1===n||3===n)return 0===e.avail_out&&(i.last_flush=-1),LO;if(2===n&&(t===OO?bO(i):t!==PO&&(vO(i,0,0,!1),t===NO&&(rN(i.head),0===i.lookahead&&(i.strstart=0,i.block_start=0,i.insert=0))),aN(e),0===e.avail_out))return i.last_flush=-1,LO}return t!==DO?LO:i.wrap<=0?kO:(2===i.wrap?(dN(i,255&e.adler),dN(i,e.adler>>8&255),dN(i,e.adler>>16&255),dN(i,e.adler>>24&255),dN(i,255&e.total_in),dN(i,e.total_in>>8&255),dN(i,e.total_in>>16&255),dN(i,e.total_in>>24&255)):(lN(i,e.adler>>>16),lN(i,65535&e.adler)),aN(e),i.wrap>0&&(i.wrap=-i.wrap),0!==i.pending?LO:kO)},yN=(e,t)=>{let i=t.length;if(SN(e))return MO;const n=e.state,r=n.wrap;if(2===r||1===r&&n.status!==$O||n.lookahead)return MO;if(1===r&&(e.adler=gO(e.adler,t,i,0)),n.wrap=0,i>=n.w_size){0===r&&(rN(n.head),n.strstart=0,n.block_start=0,n.insert=0);let e=new Uint8Array(n.w_size);e.set(t.subarray(i-n.w_size,i),0),t=e,i=n.w_size}const s=e.avail_in,o=e.next_in,a=e.input;for(e.avail_in=i,e.next_in=0,e.input=t,pN(n);n.lookahead>=3;){let e=n.strstart,t=n.lookahead-2;do{n.ins_h=oN(n,n.ins_h,n.window[e+3-1]),n.prev[e&n.w_mask]=n.head[n.ins_h],n.head[n.ins_h]=e,e++}while(--t);n.strstart=e,n.lookahead=2,pN(n)}return n.strstart+=n.lookahead,n.block_start=n.strstart,n.insert=n.lookahead,n.lookahead=0,n.match_length=n.prev_length=2,n.match_available=0,e.next_in=o,e.input=a,e.avail_in=s,n.wrap=r,LO},AN={deflateInit:(e,t)=>IN(e,t,KO,15,8,WO),deflateInit2:IN,deflateReset:CN,deflateResetKeep:RN,deflateSetHeader:(e,t)=>SN(e)||2!==e.state.wrap?MO:(e.state.gzhead=t,LO),deflate:vN,deflateEnd:e=>{if(SN(e))return MO;const t=e.state.status;return e.state=null,t===eN?iN(e,UO):LO},deflateSetDictionary:yN,deflateInfo:\"pako deflate (from Nodeca project)\"};const bN=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var wN={assign:function(e){const t=Array.prototype.slice.call(arguments,1);for(;t.length;){const i=t.shift();if(i){if(\"object\"!=typeof i)throw new TypeError(i+\"must be non-object\");for(const t in i)bN(i,t)&&(e[t]=i[t])}}return e},flattenChunks:e=>{let t=0;for(let i=0,n=e.length;i=252?6:e>=248?5:e>=240?4:e>=224?3:e>=192?2:1;NN[254]=NN[254]=1;var DN={string2buf:e=>{if(\"function\"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(e);let t,i,n,r,s,o=e.length,a=0;for(r=0;r>>6,t[s++]=128|63&i):i<65536?(t[s++]=224|i>>>12,t[s++]=128|i>>>6&63,t[s++]=128|63&i):(t[s++]=240|i>>>18,t[s++]=128|i>>>12&63,t[s++]=128|i>>>6&63,t[s++]=128|63&i);return t},buf2string:(e,t)=>{const i=t||e.length;if(\"function\"==typeof TextDecoder&&TextDecoder.prototype.decode)return(new TextDecoder).decode(e.subarray(0,t));let n,r;const s=new Array(2*i);for(r=0,n=0;n4)s[r++]=65533,n+=o-1;else{for(t&=2===o?31:3===o?15:7;o>1&&n1?s[r++]=65533:t<65536?s[r++]=t:(t-=65536,s[r++]=55296|t>>10&1023,s[r++]=56320|1023&t)}}return((e,t)=>{if(t<65534&&e.subarray&&ON)return String.fromCharCode.apply(null,e.length===t?e:e.subarray(0,t));let i=\"\";for(let n=0;n{(t=t||e.length)>e.length&&(t=e.length);let i=t-1;for(;i>=0&&128==(192&e[i]);)i--;return i<0||0===i?t:i+NN[e[i]]>t?i:t}};var PN=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg=\"\",this.state=null,this.data_type=2,this.adler=0};const LN=Object.prototype.toString,{Z_NO_FLUSH:kN,Z_SYNC_FLUSH:MN,Z_FULL_FLUSH:UN,Z_FINISH:xN,Z_OK:VN,Z_STREAM_END:FN,Z_DEFAULT_COMPRESSION:BN,Z_DEFAULT_STRATEGY:jN,Z_DEFLATED:GN}=CO;function WN(e){this.options=wN.assign({level:BN,method:GN,chunkSize:16384,windowBits:15,memLevel:8,strategy:jN},e||{});let t=this.options;t.raw&&t.windowBits>0?t.windowBits=-t.windowBits:t.gzip&&t.windowBits>0&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg=\"\",this.ended=!1,this.chunks=[],this.strm=new PN,this.strm.avail_out=0;let i=AN.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(i!==VN)throw new Error(RO[i]);if(t.header&&AN.deflateSetHeader(this.strm,t.header),t.dictionary){let e;if(e=\"string\"==typeof t.dictionary?DN.string2buf(t.dictionary):\"[object ArrayBuffer]\"===LN.call(t.dictionary)?new Uint8Array(t.dictionary):t.dictionary,i=AN.deflateSetDictionary(this.strm,e),i!==VN)throw new Error(RO[i]);this._dict_set=!0}}function HN(e,t){const i=new WN(t);if(i.push(e,!0),i.err)throw i.msg||RO[i.err];return i.result}WN.prototype.push=function(e,t){const i=this.strm,n=this.options.chunkSize;let r,s;if(this.ended)return!1;for(s=t===~~t?t:!0===t?xN:kN,\"string\"==typeof e?i.input=DN.string2buf(e):\"[object ArrayBuffer]\"===LN.call(e)?i.input=new Uint8Array(e):i.input=e,i.next_in=0,i.avail_in=i.input.length;;)if(0===i.avail_out&&(i.output=new Uint8Array(n),i.next_out=0,i.avail_out=n),(s===MN||s===UN)&&i.avail_out<=6)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else{if(r=AN.deflate(i,s),r===FN)return i.next_out>0&&this.onData(i.output.subarray(0,i.next_out)),r=AN.deflateEnd(this.strm),this.onEnd(r),this.ended=!0,r===VN;if(0!==i.avail_out){if(s>0&&i.next_out>0)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else if(0===i.avail_in)break}else this.onData(i.output)}return!0},WN.prototype.onData=function(e){this.chunks.push(e)},WN.prototype.onEnd=function(e){e===VN&&(this.result=wN.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var KN={Deflate:WN,deflate:HN,deflateRaw:function(e,t){return(t=t||{}).raw=!0,HN(e,t)},gzip:function(e,t){return(t=t||{}).gzip=!0,HN(e,t)},constants:CO};const YN=16209;var qN=function(e,t){let i,n,r,s,o,a,c,d,l,u,h,p,_,E,m,f,g,T,S,R,C,I,v,y;const A=e.state;i=e.next_in,v=e.input,n=i+(e.avail_in-5),r=e.next_out,y=e.output,s=r-(t-e.avail_out),o=r+(e.avail_out-257),a=A.dmax,c=A.wsize,d=A.whave,l=A.wnext,u=A.window,h=A.hold,p=A.bits,_=A.lencode,E=A.distcode,m=(1<>>24,h>>>=T,p-=T,T=g>>>16&255,0===T)y[r++]=65535&g;else{if(!(16&T)){if(0==(64&T)){g=_[(65535&g)+(h&(1<>>=T,p-=T),p<15&&(h+=v[i++]<>>24,h>>>=T,p-=T,T=g>>>16&255,!(16&T)){if(0==(64&T)){g=E[(65535&g)+(h&(1<a){e.msg=\"invalid distance too far back\",A.mode=YN;break e}if(h>>>=T,p-=T,T=r-s,R>T){if(T=R-T,T>d&&A.sane){e.msg=\"invalid distance too far back\",A.mode=YN;break e}if(C=0,I=u,0===l){if(C+=c-T,T2;)y[r++]=I[C++],y[r++]=I[C++],y[r++]=I[C++],S-=3;S&&(y[r++]=I[C++],S>1&&(y[r++]=I[C++]))}else{C=r-R;do{y[r++]=y[C++],y[r++]=y[C++],y[r++]=y[C++],S-=3}while(S>2);S&&(y[r++]=y[C++],S>1&&(y[r++]=y[C++]))}break}}break}}while(i>3,i-=S,p-=S<<3,h&=(1<{const c=a.bits;let d,l,u,h,p,_,E=0,m=0,f=0,g=0,T=0,S=0,R=0,C=0,I=0,v=0,y=null;const A=new Uint16Array(16),b=new Uint16Array(16);let w,O,N,D=null;for(E=0;E<=zN;E++)A[E]=0;for(m=0;m=1&&0===A[g];g--);if(T>g&&(T=g),0===g)return r[s++]=20971520,r[s++]=20971520,a.bits=1,0;for(f=1;f0&&(0===e||1!==g))return-1;for(b[1]=0,E=1;E852||2===e&&I>592)return 1;for(;;){w=E-R,o[m]+1<_?(O=0,N=o[m]):o[m]>=_?(O=D[o[m]-_],N=y[o[m]-_]):(O=96,N=0),d=1<>R)+l]=w<<24|O<<16|N|0}while(0!==l);for(d=1<>=1;if(0!==d?(v&=d-1,v+=d):v=0,m++,0==--A[E]){if(E===g)break;E=t[i+o[m]]}if(E>T&&(v&h)!==u){for(0===R&&(R=T),p+=f,S=E-R,C=1<852||2===e&&I>592)return 1;u=v&h,r[u]=T<<24|S<<16|p-s|0}}return 0!==v&&(r[p+v]=E-R<<24|64<<16|0),a.bits=T,0};const{Z_FINISH:eD,Z_BLOCK:tD,Z_TREES:iD,Z_OK:nD,Z_STREAM_END:rD,Z_NEED_DICT:sD,Z_STREAM_ERROR:oD,Z_DATA_ERROR:aD,Z_MEM_ERROR:cD,Z_BUF_ERROR:dD,Z_DEFLATED:lD}=CO,uD=16180,hD=16190,pD=16191,_D=16192,ED=16194,mD=16199,fD=16200,gD=16206,TD=16209,SD=e=>(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24);function RD(){this.strm=null,this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}const CD=e=>{if(!e)return 1;const t=e.state;return!t||t.strm!==e||t.mode16211?1:0},ID=e=>{if(CD(e))return oD;const t=e.state;return e.total_in=e.total_out=t.total=0,e.msg=\"\",t.wrap&&(e.adler=1&t.wrap),t.mode=uD,t.last=0,t.havedict=0,t.flags=-1,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new Int32Array(852),t.distcode=t.distdyn=new Int32Array(592),t.sane=1,t.back=-1,nD},vD=e=>{if(CD(e))return oD;const t=e.state;return t.wsize=0,t.whave=0,t.wnext=0,ID(e)},yD=(e,t)=>{let i;if(CD(e))return oD;const n=e.state;return t<0?(i=0,t=-t):(i=5+(t>>4),t<48&&(t&=15)),t&&(t<8||t>15)?oD:(null!==n.window&&n.wbits!==t&&(n.window=null),n.wrap=i,n.wbits=t,vD(e))},AD=(e,t)=>{if(!e)return oD;const i=new RD;e.state=i,i.strm=e,i.window=null,i.mode=uD;const n=yD(e,t);return n!==nD&&(e.state=null),n};let bD,wD,OD=!0;const ND=e=>{if(OD){bD=new Int32Array(512),wD=new Int32Array(32);let t=0;for(;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for($N(1,e.lens,0,288,bD,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;$N(2,e.lens,0,32,wD,0,e.work,{bits:5}),OD=!1}e.lencode=bD,e.lenbits=9,e.distcode=wD,e.distbits=5},DD=(e,t,i,n)=>{let r;const s=e.state;return null===s.window&&(s.wsize=1<=s.wsize?(s.window.set(t.subarray(i-s.wsize,i),0),s.wnext=0,s.whave=s.wsize):(r=s.wsize-s.wnext,r>n&&(r=n),s.window.set(t.subarray(i-n,i-n+r),s.wnext),(n-=r)?(s.window.set(t.subarray(i-n,i),0),s.wnext=n,s.whave=s.wsize):(s.wnext+=r,s.wnext===s.wsize&&(s.wnext=0),s.whave{let i,n,r,s,o,a,c,d,l,u,h,p,_,E,m,f,g,T,S,R,C,I,v=0;const y=new Uint8Array(4);let A,b;const w=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(CD(e)||!e.output||!e.input&&0!==e.avail_in)return oD;i=e.state,i.mode===pD&&(i.mode=_D),o=e.next_out,r=e.output,c=e.avail_out,s=e.next_in,n=e.input,a=e.avail_in,d=i.hold,l=i.bits,u=a,h=c,I=nD;e:for(;;)switch(i.mode){case uD:if(0===i.wrap){i.mode=_D;break}for(;l<16;){if(0===a)break e;a--,d+=n[s++]<>>8&255,i.check=SO(i.check,y,2,0),d=0,l=0,i.mode=16181;break}if(i.head&&(i.head.done=!1),!(1&i.wrap)||(((255&d)<<8)+(d>>8))%31){e.msg=\"incorrect header check\",i.mode=TD;break}if((15&d)!==lD){e.msg=\"unknown compression method\",i.mode=TD;break}if(d>>>=4,l-=4,C=8+(15&d),0===i.wbits&&(i.wbits=C),C>15||C>i.wbits){e.msg=\"invalid window size\",i.mode=TD;break}i.dmax=1<>8&1),512&i.flags&&4&i.wrap&&(y[0]=255&d,y[1]=d>>>8&255,i.check=SO(i.check,y,2,0)),d=0,l=0,i.mode=16182;case 16182:for(;l<32;){if(0===a)break e;a--,d+=n[s++]<>>8&255,y[2]=d>>>16&255,y[3]=d>>>24&255,i.check=SO(i.check,y,4,0)),d=0,l=0,i.mode=16183;case 16183:for(;l<16;){if(0===a)break e;a--,d+=n[s++]<>8),512&i.flags&&4&i.wrap&&(y[0]=255&d,y[1]=d>>>8&255,i.check=SO(i.check,y,2,0)),d=0,l=0,i.mode=16184;case 16184:if(1024&i.flags){for(;l<16;){if(0===a)break e;a--,d+=n[s++]<>>8&255,i.check=SO(i.check,y,2,0)),d=0,l=0}else i.head&&(i.head.extra=null);i.mode=16185;case 16185:if(1024&i.flags&&(p=i.length,p>a&&(p=a),p&&(i.head&&(C=i.head.extra_len-i.length,i.head.extra||(i.head.extra=new Uint8Array(i.head.extra_len)),i.head.extra.set(n.subarray(s,s+p),C)),512&i.flags&&4&i.wrap&&(i.check=SO(i.check,n,p,s)),a-=p,s+=p,i.length-=p),i.length))break e;i.length=0,i.mode=16186;case 16186:if(2048&i.flags){if(0===a)break e;p=0;do{C=n[s+p++],i.head&&C&&i.length<65536&&(i.head.name+=String.fromCharCode(C))}while(C&&p>9&1,i.head.done=!0),e.adler=i.check=0,i.mode=pD;break;case 16189:for(;l<32;){if(0===a)break e;a--,d+=n[s++]<>>=7&l,l-=7&l,i.mode=gD;break}for(;l<3;){if(0===a)break e;a--,d+=n[s++]<>>=1,l-=1,3&d){case 0:i.mode=16193;break;case 1:if(ND(i),i.mode=mD,t===iD){d>>>=2,l-=2;break e}break;case 2:i.mode=16196;break;case 3:e.msg=\"invalid block type\",i.mode=TD}d>>>=2,l-=2;break;case 16193:for(d>>>=7&l,l-=7&l;l<32;){if(0===a)break e;a--,d+=n[s++]<>>16^65535)){e.msg=\"invalid stored block lengths\",i.mode=TD;break}if(i.length=65535&d,d=0,l=0,i.mode=ED,t===iD)break e;case ED:i.mode=16195;case 16195:if(p=i.length,p){if(p>a&&(p=a),p>c&&(p=c),0===p)break e;r.set(n.subarray(s,s+p),o),a-=p,s+=p,c-=p,o+=p,i.length-=p;break}i.mode=pD;break;case 16196:for(;l<14;){if(0===a)break e;a--,d+=n[s++]<>>=5,l-=5,i.ndist=1+(31&d),d>>>=5,l-=5,i.ncode=4+(15&d),d>>>=4,l-=4,i.nlen>286||i.ndist>30){e.msg=\"too many length or distance symbols\",i.mode=TD;break}i.have=0,i.mode=16197;case 16197:for(;i.have>>=3,l-=3}for(;i.have<19;)i.lens[w[i.have++]]=0;if(i.lencode=i.lendyn,i.lenbits=7,A={bits:i.lenbits},I=$N(0,i.lens,0,19,i.lencode,0,i.work,A),i.lenbits=A.bits,I){e.msg=\"invalid code lengths set\",i.mode=TD;break}i.have=0,i.mode=16198;case 16198:for(;i.have>>24,f=v>>>16&255,g=65535&v,!(m<=l);){if(0===a)break e;a--,d+=n[s++]<>>=m,l-=m,i.lens[i.have++]=g;else{if(16===g){for(b=m+2;l>>=m,l-=m,0===i.have){e.msg=\"invalid bit length repeat\",i.mode=TD;break}C=i.lens[i.have-1],p=3+(3&d),d>>>=2,l-=2}else if(17===g){for(b=m+3;l>>=m,l-=m,C=0,p=3+(7&d),d>>>=3,l-=3}else{for(b=m+7;l>>=m,l-=m,C=0,p=11+(127&d),d>>>=7,l-=7}if(i.have+p>i.nlen+i.ndist){e.msg=\"invalid bit length repeat\",i.mode=TD;break}for(;p--;)i.lens[i.have++]=C}}if(i.mode===TD)break;if(0===i.lens[256]){e.msg=\"invalid code -- missing end-of-block\",i.mode=TD;break}if(i.lenbits=9,A={bits:i.lenbits},I=$N(1,i.lens,0,i.nlen,i.lencode,0,i.work,A),i.lenbits=A.bits,I){e.msg=\"invalid literal/lengths set\",i.mode=TD;break}if(i.distbits=6,i.distcode=i.distdyn,A={bits:i.distbits},I=$N(2,i.lens,i.nlen,i.ndist,i.distcode,0,i.work,A),i.distbits=A.bits,I){e.msg=\"invalid distances set\",i.mode=TD;break}if(i.mode=mD,t===iD)break e;case mD:i.mode=fD;case fD:if(a>=6&&c>=258){e.next_out=o,e.avail_out=c,e.next_in=s,e.avail_in=a,i.hold=d,i.bits=l,qN(e,h),o=e.next_out,r=e.output,c=e.avail_out,s=e.next_in,n=e.input,a=e.avail_in,d=i.hold,l=i.bits,i.mode===pD&&(i.back=-1);break}for(i.back=0;v=i.lencode[d&(1<>>24,f=v>>>16&255,g=65535&v,!(m<=l);){if(0===a)break e;a--,d+=n[s++]<>T)],m=v>>>24,f=v>>>16&255,g=65535&v,!(T+m<=l);){if(0===a)break e;a--,d+=n[s++]<>>=T,l-=T,i.back+=T}if(d>>>=m,l-=m,i.back+=m,i.length=g,0===f){i.mode=16205;break}if(32&f){i.back=-1,i.mode=pD;break}if(64&f){e.msg=\"invalid literal/length code\",i.mode=TD;break}i.extra=15&f,i.mode=16201;case 16201:if(i.extra){for(b=i.extra;l>>=i.extra,l-=i.extra,i.back+=i.extra}i.was=i.length,i.mode=16202;case 16202:for(;v=i.distcode[d&(1<>>24,f=v>>>16&255,g=65535&v,!(m<=l);){if(0===a)break e;a--,d+=n[s++]<>T)],m=v>>>24,f=v>>>16&255,g=65535&v,!(T+m<=l);){if(0===a)break e;a--,d+=n[s++]<>>=T,l-=T,i.back+=T}if(d>>>=m,l-=m,i.back+=m,64&f){e.msg=\"invalid distance code\",i.mode=TD;break}i.offset=g,i.extra=15&f,i.mode=16203;case 16203:if(i.extra){for(b=i.extra;l>>=i.extra,l-=i.extra,i.back+=i.extra}if(i.offset>i.dmax){e.msg=\"invalid distance too far back\",i.mode=TD;break}i.mode=16204;case 16204:if(0===c)break e;if(p=h-c,i.offset>p){if(p=i.offset-p,p>i.whave&&i.sane){e.msg=\"invalid distance too far back\",i.mode=TD;break}p>i.wnext?(p-=i.wnext,_=i.wsize-p):_=i.wnext-p,p>i.length&&(p=i.length),E=i.window}else E=r,_=o-i.offset,p=i.length;p>c&&(p=c),c-=p,i.length-=p;do{r[o++]=E[_++]}while(--p);0===i.length&&(i.mode=fD);break;case 16205:if(0===c)break e;r[o++]=i.length,c--,i.mode=fD;break;case gD:if(i.wrap){for(;l<32;){if(0===a)break e;a--,d|=n[s++]<AD(e,15),inflateInit2:AD,inflate:PD,inflateEnd:e=>{if(CD(e))return oD;let t=e.state;return t.window&&(t.window=null),e.state=null,nD},inflateGetHeader:(e,t)=>{if(CD(e))return oD;const i=e.state;return 0==(2&i.wrap)?oD:(i.head=t,t.done=!1,nD)},inflateSetDictionary:(e,t)=>{const i=t.length;let n,r,s;return CD(e)?oD:(n=e.state,0!==n.wrap&&n.mode!==hD?oD:n.mode===hD&&(r=1,r=gO(r,t,i,0),r!==n.check)?aD:(s=DD(e,t,i,i),s?(n.mode=16210,cD):(n.havedict=1,nD)))},inflateInfo:\"pako inflate (from Nodeca project)\"};var kD=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name=\"\",this.comment=\"\",this.hcrc=0,this.done=!1};const MD=Object.prototype.toString,{Z_NO_FLUSH:UD,Z_FINISH:xD,Z_OK:VD,Z_STREAM_END:FD,Z_NEED_DICT:BD,Z_STREAM_ERROR:jD,Z_DATA_ERROR:GD,Z_MEM_ERROR:WD}=CO;function HD(e){this.options=wN.assign({chunkSize:65536,windowBits:15,to:\"\"},e||{});const t=this.options;t.raw&&t.windowBits>=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(t.windowBits>=0&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&0==(15&t.windowBits)&&(t.windowBits|=15),this.err=0,this.msg=\"\",this.ended=!1,this.chunks=[],this.strm=new PN,this.strm.avail_out=0;let i=LD.inflateInit2(this.strm,t.windowBits);if(i!==VD)throw new Error(RO[i]);if(this.header=new kD,LD.inflateGetHeader(this.strm,this.header),t.dictionary&&(\"string\"==typeof t.dictionary?t.dictionary=DN.string2buf(t.dictionary):\"[object ArrayBuffer]\"===MD.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(i=LD.inflateSetDictionary(this.strm,t.dictionary),i!==VD)))throw new Error(RO[i])}function KD(e,t){const i=new HD(t);if(i.push(e),i.err)throw i.msg||RO[i.err];return i.result}HD.prototype.push=function(e,t){const i=this.strm,n=this.options.chunkSize,r=this.options.dictionary;let s,o,a;if(this.ended)return!1;for(o=t===~~t?t:!0===t?xD:UD,\"[object ArrayBuffer]\"===MD.call(e)?i.input=new Uint8Array(e):i.input=e,i.next_in=0,i.avail_in=i.input.length;;){for(0===i.avail_out&&(i.output=new Uint8Array(n),i.next_out=0,i.avail_out=n),s=LD.inflate(i,o),s===BD&&r&&(s=LD.inflateSetDictionary(i,r),s===VD?s=LD.inflate(i,o):s===GD&&(s=BD));i.avail_in>0&&s===FD&&i.state.wrap>0&&0!==e[i.next_in];)LD.inflateReset(i),s=LD.inflate(i,o);switch(s){case jD:case GD:case BD:case WD:return this.onEnd(s),this.ended=!0,!1}if(a=i.avail_out,i.next_out&&(0===i.avail_out||s===FD))if(\"string\"===this.options.to){let e=DN.utf8border(i.output,i.next_out),t=i.next_out-e,r=DN.buf2string(i.output,e);i.next_out=t,i.avail_out=n-t,t&&i.output.set(i.output.subarray(e,e+t),0),this.onData(r)}else this.onData(i.output.length===i.next_out?i.output:i.output.subarray(0,i.next_out));if(s!==VD||0!==a){if(s===FD)return s=LD.inflateEnd(this.strm),this.onEnd(s),this.ended=!0,!0;if(0===i.avail_in)break}}return!0},HD.prototype.onData=function(e){this.chunks.push(e)},HD.prototype.onEnd=function(e){e===VD&&(\"string\"===this.options.to?this.result=this.chunks.join(\"\"):this.result=wN.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var YD={Inflate:HD,inflate:KD,inflateRaw:function(e,t){return(t=t||{}).raw=!0,KD(e,t)},ungzip:KD,constants:CO};const{Deflate:qD,deflate:zD,deflateRaw:JD,gzip:XD}=KN,{Inflate:QD,inflate:ZD,inflateRaw:$D,ungzip:eP}=YD;var tP,iP=zD,nP=ZD;!function(e){e[e.ONE_BYTE=0]=\"ONE_BYTE\",e[e.TWO_BYTE=1]=\"TWO_BYTE\"}(tP||(tP={}));class rP{constructor(){sh(this,\"_sequence\",0),sh(this,\"_startTime\",Date.now()),sh(this,\"isUseOneByte\",!0)}get startTime(){const e=Date.now()-this._startTime;return e128){const i=new Uint8Array(4);i.set([1,0,0,0]);const n={id:0,length:4,data:i.buffer},r={profile:this.isUseOneByte?0:1,length:this.isUseOneByte?5:6,datas:[n]};t.commonPacketHeader.extension=1,t.extension=r,t.payload=this.compress(e),t.commonPacketHeader.length=8+(t.extension.length+2)+t.payload.byteLength}else t.commonPacketHeader.length=8+t.payload.byteLength;RC(\"SHOW_DATASTREAM2_LOG\")&&jC.debug(\"send data header: \".concat(JSON.stringify(t.commonPacketHeader)));const i=new ArrayBuffer(t.commonPacketHeader.length),n=new Uint8Array(i),r=new DataView(i);let s=0;if(r.setUint16(s,t.commonPacketHeader.extension<<15|t.commonPacketHeader.reserved<<14|t.commonPacketHeader.length,!0),s+=2,r.setUint32(s,t.commonPacketHeader.sequence,!0),s+=4,r.setUint16(s,t.commonStreamHeader,!0),s+=2,t.extension){const e=this.serializeExtension(t.extension);n.set(new Uint8Array(e),s),s+=e.byteLength}if(n.set(new Uint8Array(t.payload),s),s+=t.payload.byteLength,s!==t.commonPacketHeader.length)throw Error(\"serialize error!\");return i}deserialize(e){if(e.byteLength<4)return new ArrayBuffer(0);const t=new DataView(e);let i=0;const n=t.getUint16(i,!0);i+=2;const r={length:16383&n,reserved:(16384&n)>>14,extension:(32768&n)>>15,sequence:t.getUint16(i+2,!0)<<16|t.getUint16(i,!0)};let s,o;if(i+=4,RC(\"SHOW_DATASTREAM2_LOG\")&&jC.debug(\"receive data header: \".concat(JSON.stringify(r))),t.getUint16(i,!0),i+=2,r.extension){o=this.deserializeExtension(e.slice(i)),i+=2+o.length,s=e.slice(i);let t=!1;if(o.datas.length>0){const e=o.datas.find((e=>0===e.id));if(e){t=1==(1&new DataView(e.data).getUint32(0,!0))}}s=t?this.decompress(s):s}else s=e.slice(8);return s}serializeExtension(e){const{profile:t,length:i,datas:n}=e,r=new ArrayBuffer(i+2),s=new Uint8Array(r),o=new DataView(r);let a=0;if(o.setUint8(a++,t),o.setUint8(a++,i),n.forEach((e=>{t?(o.setUint8(a++,e.id),o.setUint8(a++,e.length),s.set(new Uint8Array(e.data),a),a+=e.data.byteLength):(o.setUint8(a++,e.id|e.length<<4),s.set(new Uint8Array(e.data),a),a+=e.data.byteLength)})),a!==i+2)throw Error(\"serialize extension error, is \".concat(a,\"!==\").concat(i+2));return r}deserializeExtension(e){const t=new DataView(e);let i=0;const n=t.getUint8(i);i++;const r=t.getUint8(i);i++;const s=n===tP.TWO_BYTE,o=[],a=new DataView(e,2);let c=0;for(;c>4,c++),t>0&&(i=a.buffer.slice(c+2,c+2+t),c+=i.byteLength),o.push({id:e,length:t,data:i})}if(c!==r)throw Error(\"parse error\");return{profile:n,length:r,datas:o}}decompress(e){return nP(new Uint8Array(e))}compress(e){return iP(new Uint8Array(e))}}class sP extends dT{constructor(e,t){super(),sh(this,\"_version\",1),sh(this,\"_type\",3),sh(this,\"_config\",void 0),sh(this,\"_originDataChannel\",void 0),sh(this,\"_dataStreamPacketHeader\",new ArrayBuffer(4)),sh(this,\"_dataStreamPacketHandler\",void 0),sh(this,\"_datachannelEventMap\",new Map),this._config=e,t&&(this._originDataChannel=t,this._bandDataChannelEvents(t)),this._initPacketHeader(),this._dataStreamPacketHandler=new rP}get id(){return this._config.id}get ordered(){return this._config.ordered}get maxRetransmits(){return RC(\"DATASTREAM_MAX_RETRANSMITS\")}get metadata(){return this._config.metadata}get readyState(){var e,t;return null!==(e=null===(t=this._originDataChannel)||void 0===t?void 0:t.readyState)&&void 0!==e?e:\"connecting\"}get _originDataChannelId(){var e,t;return null!==(e=null===(t=this._originDataChannel)||void 0===t?void 0:t.id)&&void 0!==e?e:null}getChannelId(){return this.id}getConfig(){return this._config}_close(){this._originDataChannel&&(this._unbindDataChannelEvents(this._originDataChannel),this._originDataChannel=void 0)}async _waitTillOpen(){return new cg(((e,t)=>{if(this._originDataChannel){\"open\"===this._originDataChannel.readyState&&e();const i=setTimeout((()=>{var e;t(new Kg(Hg.DATACHANNEL_CONNECTION_TIMEOUT,\"Cannot create datachannel, id: \".concat(null===(e=this._originDataChannel)||void 0===e?void 0:e.id)))}),1e4);this._originDataChannel.onopen=()=>{clearTimeout(i),this._originDataChannel&&this._bandDataChannelEvents(this._originDataChannel),e()},this._originDataChannel.onerror=()=>{throw clearTimeout(i),new Kg(Hg.DATACHANNEL_CONNECTION_TIMEOUT)}}else t(new Kg(Hg.DATACHANNEL_CONNECTION_TIMEOUT,\"cannot find dataChannel\"))}))}_updateOriginDataChannel(e){this._originDataChannel=e,this._bandDataChannelEvents(e)}_initPacketHeader(){const e=new DataView(this._dataStreamPacketHeader);e.setUint16(0,this._version),e.setUint8(2,this._type),e.setUint8(3,this._config.id)}_bandDataChannelEvents(e){this._unbindDataChannelEvents(e),[cb.OPEN,cb.CLOSE,cb.ERROR].forEach((t=>{const i=()=>{this.emit(t)};this._datachannelEventMap.set(t,i),e.addEventListener(t,i)}))}_unbindDataChannelEvents(e){Array.from(this._datachannelEventMap.entries()).forEach((t=>{let[i,n]=t;e.removeEventListener(i,n)})),this._datachannelEventMap.clear()}}class oP extends sP{constructor(e){super(e),sh(this,\"_messageListener\",void 0),this._messageListener=e=>{if(e.data.byteLength0?arguments[0]:void 0));mP||(this.size=e.entries.length)},RL=SL.prototype;if(SP(RL,{append:function(e,t){var i=GP(this);UP(arguments.length,2),nL(i.entries,{key:DP(e),value:DP(t)}),mP||this.length++,i.updateURL()},delete:function(e){for(var t=GP(this),i=UP(arguments.length,1),n=t.entries,r=DP(e),s=i<2?void 0:arguments[1],o=void 0===s?s:DP(s),a=0;at.key?1:-1})),e.updateURL()},forEach:function(e){for(var t,i=GP(this).entries,n=bP(e,arguments.length>1?arguments[1]:void 0),r=0;r1?vL(arguments[1]):{})}}),yP(qP)){var yL=function(e){return vP(this,JP),new qP(e,arguments.length>1?vL(arguments[1]):{})};JP.constructor=yL,yL.prototype=JP,hP({global:!0,constructor:!0,dontCallGetSet:!0,forced:!0},{Request:yL})}}var AL,bL={URLSearchParams:SL,getState:GP},wL=N,OL=d,NL=L,DL=n,PL=Ys,LL=ko,kL=k,ML=Je,UL=K,xL=Object.assign,VL=Object.defineProperty,FL=OL([].concat),BL=!xL||DL((function(){if(wL&&1!==xL({b:1},xL(VL({},\"a\",{enumerable:!0,get:function(){VL(this,\"b\",{value:3,enumerable:!1})}}),{b:2})).b)return!0;var e={},t={},i=Symbol(),n=\"abcdefghijklmnopqrst\";return e[i]=7,n.split(\"\").forEach((function(e){t[e]=e})),7!=xL({},e)[i]||PL(xL({},t)).join(\"\")!=n}))?function(e,t){for(var i=ML(e),n=arguments.length,r=1,s=LL.f,o=kL.f;n>r;)for(var a,c=UL(arguments[r++]),d=s?FL(PL(c),s(c)):PL(c),l=d.length,u=0;l>u;)a=d[u++],wL&&!NL(o,c,a)||(i[a]=c[a]);return i}:xL,jL=ii,GL=Hp,WL=Xt,HL=L,KL=Je,YL=function(e,t,i,n){try{return n?t(jL(i)[0],i[1]):t(i)}catch(t){GL(e,\"throw\",t)}},qL=bp,zL=ls,JL=Bi,XL=Yr,QL=Bp,ZL=Lp,$L=Array,ek=d,tk=2147483647,ik=/[^\\0-\\u007E]/,nk=/[.\\u3002\\uFF0E\\uFF61]/g,rk=\"Overflow: input needs wider integers to process\",sk=RangeError,ok=ek(nk.exec),ak=Math.floor,ck=String.fromCharCode,dk=ek(\"\".charCodeAt),lk=ek([].join),uk=ek([].push),hk=ek(\"\".replace),pk=ek(\"\".split),_k=ek(\"\".toLowerCase),Ek=function(e){return e+22+75*(e<26)},mk=function(e,t,i){var n=0;for(e=i?ak(e/700):e>>1,e+=ak(e/t);e>455;)e=ak(e/35),n+=36;return ak(n+36*e/(e+38))},fk=function(e){var t=[];e=function(e){for(var t=[],i=0,n=e.length;i=55296&&r<=56319&&i=s&&nak((tk-o)/u))throw sk(rk);for(o+=(l-s)*u,s=l,i=0;itk)throw sk(rk);if(n==s){for(var h=o,p=36;;){var _=p<=a?1:p>=a+26?26:p-a;if(h<_)break;var E=h-_,m=36-_;uk(t,ck(Ek(_+E%m))),h=ak(E/m),p+=36}uk(t,ck(Ek(h))),a=mk(o,u,d==c),o=0,d++}}o++,s++}return lk(t,\"\")},gk=wi,Tk=N,Sk=lP,Rk=h,Ck=Xt,Ik=d,vk=Uo,yk=Vo,Ak=k_,bk=Ze,wk=BL,Ok=function(e){var t=KL(e),i=zL(this),n=arguments.length,r=n>1?arguments[1]:void 0,s=void 0!==r;s&&(r=WL(r,n>2?arguments[2]:void 0));var o,a,c,d,l,u,h=ZL(t),p=0;if(!h||this===$L&&qL(h))for(o=JL(t),a=i?new this(o):$L(o);o>p;p++)u=s?r(t[p],p):t[p],XL(a,p,u);else for(l=(d=QL(t,h)).next,a=i?new this:[];!(c=HL(l,d)).done;p++)u=s?YL(d,r,[c.value,p],!0):c.value,XL(a,p,u);return a.length=p,a},Nk=wo,Dk=Yu.codeAt,Pk=function(e){var t,i,n=[],r=pk(hk(_k(e),nk,\".\"),\".\");for(t=0;t?@[\\\\\\]^|]/,mM=/[\\0\\t\\n\\r #/:<>?@[\\\\\\]^|]/,fM=/^[\\u0000-\\u0020]+/,gM=/(^|[^\\u0000-\\u0020])[\\u0000-\\u0020]+$/,TM=/[\\t\\n\\r]/g,SM=function(e){var t,i,n,r;if(\"number\"==typeof e){for(t=[],i=0;i<4;i++)rM(t,e%256),e=Kk(e/256);return Jk(t,\".\")}if(\"object\"==typeof e){for(t=\"\",n=function(e){for(var t=null,i=1,n=null,r=0,s=0;s<8;s++)0!==e[s]?(r>i&&(t=n,i=r),n=null,r=0):(null===n&&(n=s),++r);return r>i&&(t=n,i=r),t}(e),i=0;i<8;i++)r&&0===e[i]||(r&&(r=!1),n===i?(t+=i?\":\":\"::\",r=!0):(t+=Xk(e[i],16),i<7&&(t+=\":\")));return\"[\"+t+\"]\"}return e},RM={},CM=wk({},RM,{\" \":1,'\"':1,\"<\":1,\">\":1,\"`\":1}),IM=wk({},CM,{\"#\":1,\"?\":1,\"{\":1,\"}\":1}),vM=wk({},IM,{\"/\":1,\":\":1,\";\":1,\"=\":1,\"@\":1,\"[\":1,\"\\\\\":1,\"]\":1,\"^\":1,\"|\":1}),yM=function(e,t){var i=Dk(e,0);return i>32&&i<127&&!bk(t,e)?e:encodeURIComponent(e)},AM={ftp:21,file:null,http:80,https:443,ws:80,wss:443},bM=function(e,t){var i;return 2==e.length&&zk(cM,qk(e,0))&&(\":\"==(i=qk(e,1))||!t&&\"|\"==i)},wM=function(e){var t;return e.length>1&&bM(iM(e,0,2))&&(2==e.length||\"/\"===(t=qk(e,2))||\"\\\\\"===t||\"?\"===t||\"#\"===t)},OM=function(e){return\".\"===e||\"%2e\"===nM(e)},NM={},DM={},PM={},LM={},kM={},MM={},UM={},xM={},VM={},FM={},BM={},jM={},GM={},WM={},HM={},KM={},YM={},qM={},zM={},JM={},XM={},QM=function(e,t,i){var n,r,s,o=Lk(e);if(t){if(r=this.parse(o))throw Wk(r);this.searchParams=null}else{if(void 0!==i&&(n=new QM(i,!0)),r=this.parse(o,null,n))throw Wk(r);(s=jk(new Bk)).bindURL(this),this.searchParams=s}};QM.prototype={type:\"URL\",parse:function(e,t,i){var n,r,s,o,a,c=this,d=t||NM,l=0,u=\"\",h=!1,p=!1,_=!1;for(e=Lk(e),t||(c.scheme=\"\",c.username=\"\",c.password=\"\",c.host=null,c.port=null,c.path=[],c.query=null,c.fragment=null,c.cannotBeABaseURL=!1,e=$k(e,fM,\"\"),e=$k(e,gM,\"$1\")),e=$k(e,TM,\"\"),n=Ok(e);l<=n.length;){switch(r=n[l],d){case NM:if(!r||!zk(cM,r)){if(t)return sM;d=PM;continue}u+=nM(r),d=DM;break;case DM:if(r&&(zk(dM,r)||\"+\"==r||\"-\"==r||\".\"==r))u+=nM(r);else{if(\":\"!=r){if(t)return sM;u=\"\",d=PM,l=0;continue}if(t&&(c.isSpecial()!=bk(AM,u)||\"file\"==u&&(c.includesCredentials()||null!==c.port)||\"file\"==c.scheme&&!c.host))return;if(c.scheme=u,t)return void(c.isSpecial()&&AM[c.scheme]==c.port&&(c.port=null));u=\"\",\"file\"==c.scheme?d=WM:c.isSpecial()&&i&&i.scheme==c.scheme?d=LM:c.isSpecial()?d=xM:\"/\"==n[l+1]?(d=kM,l++):(c.cannotBeABaseURL=!0,Zk(c.path,\"\"),d=zM)}break;case PM:if(!i||i.cannotBeABaseURL&&\"#\"!=r)return sM;if(i.cannotBeABaseURL&&\"#\"==r){c.scheme=i.scheme,c.path=Nk(i.path),c.query=i.query,c.fragment=\"\",c.cannotBeABaseURL=!0,d=XM;break}d=\"file\"==i.scheme?WM:MM;continue;case LM:if(\"/\"!=r||\"/\"!=n[l+1]){d=MM;continue}d=VM,l++;break;case kM:if(\"/\"==r){d=FM;break}d=qM;continue;case MM:if(c.scheme=i.scheme,r==AL)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=Nk(i.path),c.query=i.query;else if(\"/\"==r||\"\\\\\"==r&&c.isSpecial())d=UM;else if(\"?\"==r)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=Nk(i.path),c.query=\"\",d=JM;else{if(\"#\"!=r){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=Nk(i.path),c.path.length--,d=qM;continue}c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=Nk(i.path),c.query=i.query,c.fragment=\"\",d=XM}break;case UM:if(!c.isSpecial()||\"/\"!=r&&\"\\\\\"!=r){if(\"/\"!=r){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,d=qM;continue}d=FM}else d=VM;break;case xM:if(d=VM,\"/\"!=r||\"/\"!=qk(u,l+1))continue;l++;break;case VM:if(\"/\"!=r&&\"\\\\\"!=r){d=FM;continue}break;case FM:if(\"@\"==r){h&&(u=\"%40\"+u),h=!0,s=Ok(u);for(var E=0;E65535)return aM;c.port=c.isSpecial()&&g===AM[c.scheme]?null:g,u=\"\"}if(t)return;d=YM;continue}return aM}u+=r;break;case WM:if(c.scheme=\"file\",\"/\"==r||\"\\\\\"==r)d=HM;else{if(!i||\"file\"!=i.scheme){d=qM;continue}if(r==AL)c.host=i.host,c.path=Nk(i.path),c.query=i.query;else if(\"?\"==r)c.host=i.host,c.path=Nk(i.path),c.query=\"\",d=JM;else{if(\"#\"!=r){wM(Jk(Nk(n,l),\"\"))||(c.host=i.host,c.path=Nk(i.path),c.shortenPath()),d=qM;continue}c.host=i.host,c.path=Nk(i.path),c.query=i.query,c.fragment=\"\",d=XM}}break;case HM:if(\"/\"==r||\"\\\\\"==r){d=KM;break}i&&\"file\"==i.scheme&&!wM(Jk(Nk(n,l),\"\"))&&(bM(i.path[0],!0)?Zk(c.path,i.path[0]):c.host=i.host),d=qM;continue;case KM:if(r==AL||\"/\"==r||\"\\\\\"==r||\"?\"==r||\"#\"==r){if(!t&&bM(u))d=qM;else if(\"\"==u){if(c.host=\"\",t)return;d=YM}else{if(o=c.parseHost(u))return o;if(\"localhost\"==c.host&&(c.host=\"\"),t)return;u=\"\",d=YM}continue}u+=r;break;case YM:if(c.isSpecial()){if(d=qM,\"/\"!=r&&\"\\\\\"!=r)continue}else if(t||\"?\"!=r)if(t||\"#\"!=r){if(r!=AL&&(d=qM,\"/\"!=r))continue}else c.fragment=\"\",d=XM;else c.query=\"\",d=JM;break;case qM:if(r==AL||\"/\"==r||\"\\\\\"==r&&c.isSpecial()||!t&&(\"?\"==r||\"#\"==r)){if(\"..\"===(a=nM(a=u))||\"%2e.\"===a||\".%2e\"===a||\"%2e%2e\"===a?(c.shortenPath(),\"/\"==r||\"\\\\\"==r&&c.isSpecial()||Zk(c.path,\"\")):OM(u)?\"/\"==r||\"\\\\\"==r&&c.isSpecial()||Zk(c.path,\"\"):(\"file\"==c.scheme&&!c.path.length&&bM(u)&&(c.host&&(c.host=\"\"),u=qk(u,0)+\":\"),Zk(c.path,u)),u=\"\",\"file\"==c.scheme&&(r==AL||\"?\"==r||\"#\"==r))for(;c.path.length>1&&\"\"===c.path[0];)eM(c.path);\"?\"==r?(c.query=\"\",d=JM):\"#\"==r&&(c.fragment=\"\",d=XM)}else u+=yM(r,IM);break;case zM:\"?\"==r?(c.query=\"\",d=JM):\"#\"==r?(c.fragment=\"\",d=XM):r!=AL&&(c.path[0]+=yM(r,RM));break;case JM:t||\"#\"!=r?r!=AL&&(\"'\"==r&&c.isSpecial()?c.query+=\"%27\":c.query+=\"#\"==r?\"%23\":yM(r,RM)):(c.fragment=\"\",d=XM);break;case XM:r!=AL&&(c.fragment+=yM(r,CM))}l++}},parseHost:function(e){var t,i,n;if(\"[\"==qk(e,0)){if(\"]\"!=qk(e,e.length-1))return oM;if(t=function(e){var t,i,n,r,s,o,a,c=[0,0,0,0,0,0,0,0],d=0,l=null,u=0,h=function(){return qk(e,u)};if(\":\"==h()){if(\":\"!=qk(e,1))return;u+=2,l=++d}for(;h();){if(8==d)return;if(\":\"!=h()){for(t=i=0;i<4&&zk(_M,h());)t=16*t+Hk(h(),16),u++,i++;if(\".\"==h()){if(0==i)return;if(u-=i,d>6)return;for(n=0;h();){if(r=null,n>0){if(!(\".\"==h()&&n<4))return;u++}if(!zk(lM,h()))return;for(;zk(lM,h());){if(s=Hk(h(),10),null===r)r=s;else{if(0==r)return;r=10*r+s}if(r>255)return;u++}c[d]=256*c[d]+r,2!=++n&&4!=n||d++}if(4!=n)return;break}if(\":\"==h()){if(u++,!h())return}else if(h())return;c[d++]=t}else{if(null!==l)return;u++,l=++d}}if(null!==l)for(o=d-l,d=7;0!=d&&o>0;)a=c[d],c[d--]=c[l+o-1],c[l+--o]=a;else if(8!=d)return;return c}(iM(e,1,-1)),!t)return oM;this.host=t}else if(this.isSpecial()){if(e=Pk(e),zk(EM,e))return oM;if(t=function(e){var t,i,n,r,s,o,a,c=tM(e,\".\");if(c.length&&\"\"==c[c.length-1]&&c.length--,(t=c.length)>4)return e;for(i=[],n=0;n1&&\"0\"==qk(r,0)&&(s=zk(uM,r)?16:8,r=iM(r,8==s?1:2)),\"\"===r)o=0;else{if(!zk(10==s?pM:8==s?hM:_M,r))return e;o=Hk(r,s)}Zk(i,o)}for(n=0;n=Yk(256,5-t))return null}else if(o>255)return null;for(a=Qk(i),n=0;n1?arguments[1]:void 0,n=Vk(t,new QM(e,!1,i));Tk||(t.href=n.serialize(),t.origin=n.getOrigin(),t.protocol=n.getProtocol(),t.username=n.getUsername(),t.password=n.getPassword(),t.host=n.getHost(),t.hostname=n.getHostname(),t.port=n.getPort(),t.pathname=n.getPathname(),t.search=n.getSearch(),t.searchParams=n.getSearchParams(),t.hash=n.getHash())},$M=ZM.prototype,eU=function(e,t){return{get:function(){return Fk(this)[e]()},set:t&&function(e){return Fk(this)[t](e)},configurable:!0,enumerable:!0}};if(Tk&&(yk($M,\"href\",eU(\"serialize\",\"setHref\")),yk($M,\"origin\",eU(\"getOrigin\")),yk($M,\"protocol\",eU(\"getProtocol\",\"setProtocol\")),yk($M,\"username\",eU(\"getUsername\",\"setUsername\")),yk($M,\"password\",eU(\"getPassword\",\"setPassword\")),yk($M,\"host\",eU(\"getHost\",\"setHost\")),yk($M,\"hostname\",eU(\"getHostname\",\"setHostname\")),yk($M,\"port\",eU(\"getPort\",\"setPort\")),yk($M,\"pathname\",eU(\"getPathname\",\"setPathname\")),yk($M,\"search\",eU(\"getSearch\",\"setSearch\")),yk($M,\"searchParams\",eU(\"getSearchParams\")),yk($M,\"hash\",eU(\"getHash\",\"setHash\"))),vk($M,\"toJSON\",(function(){return Fk(this).serialize()}),{enumerable:!0}),vk($M,\"toString\",(function(){return Fk(this).serialize()}),{enumerable:!0}),Gk){var tU=Gk.createObjectURL,iU=Gk.revokeObjectURL;tU&&vk(ZM,\"createObjectURL\",Ck(tU,Gk)),iU&&vk(ZM,\"revokeObjectURL\",Ck(iU,Gk))}kk(ZM,\"URL\"),gk({global:!0,constructor:!0,forced:!Sk,sham:!Tk},{URL:ZM});var nU=wi,rU=n,sU=H_,oU=pn,aU=lP,cU=ae(\"URL\");nU({target:\"URL\",stat:!0,forced:!(aU&&rU((function(){cU.canParse()})))},{canParse:function(e){var t=sU(arguments.length,1),i=oU(e),n=t<2||void 0===arguments[1]?void 0:oU(arguments[1]);try{return!!new cU(i,n)}catch(e){return!1}}});var dU=i(ie.URL);function lU(){const e=new Blob([atob(\"ZnVuY3Rpb24gZShlKXtjb25zdCB0PW5ldyBEYXRhVmlldyhlLmRhdGEpO2lmKDA9PT10LmdldFVpbnQ4KDApJiYwPT09dC5nZXRVaW50OCgxKSYmMD09PXQuZ2V0VWludDgoMikmJjE9PT10LmdldFVpbnQ4KDMpJiY2PT09dC5nZXRVaW50OCg0KSl7bGV0IG49NixyPTAsbz0wO2Zvcig7MjU1PT09KG89dC5nZXRVaW50OChuKyspKTspcis9MjU1O3IrPW87Y29uc3QgYT1mdW5jdGlvbihlLHQsbil7bGV0IHI9bmV3IFVpbnQ4QXJyYXkoZSx0LG4pLG89W10sYT0wO2Zvcig7YTxuOylhKzM8biYmMD09PXJbYV0mJjA9PT1yW2ErMV0mJjM9PT1yW2ErMl0mJigwPT09clthKzNdfHwxPT09clthKzNdfHwyPT09clthKzNdfHwzPT09clthKzNdKT8oby5wdXNoKHJbYV0sclthKzFdLHJbYSszXSksYSs9NCk6KG8ucHVzaChyW2FdKSxhKyspO3JldHVybiBuZXcgVWludDhBcnJheShvKX0oZS5kYXRhLG4scik7cmV0dXJuIG5ldyBVaW50OEFycmF5KGEpfXJldHVybiBudWxsfWZ1bmN0aW9uIHQoZSx0KXtjb25zdCBuPWZ1bmN0aW9uKGUpe2NvbnN0IHQ9ZS5sZW5ndGg7bGV0IG49W10scj0wO2Zvcig7cjx0OylyKzI8dCYmMD09PWVbcl0mJjA9PT1lW3IrMV0mJigwPT09ZVtyKzJdfHwxPT09ZVtyKzJdfHwyPT09ZVtyKzJdfHwzPT09ZVtyKzJdKT8obi5wdXNoKGVbcl0sZVtyKzFdLDMsZVtyKzJdKSxyKz0zKToobi5wdXNoKGVbcl0pLHIrKyk7cmV0dXJuIG5ldyBVaW50OEFycmF5KG4pfSh0KSxyPW4ubGVuZ3RoLG89TWF0aC5mbG9vcihyLzI1NSksYT1yJTI1NSxzPW5ldyBVaW50OEFycmF5KDYrbysxK3IrZS5ieXRlTGVuZ3RoKTtzWzBdPTAsc1sxXT0wLHNbMl09MCxzWzNdPTEsc1s0XT02LHNbNV09MTAxO2xldCBpPTA7Zm9yKDtpPG87KXNbNitpXT0yNTUsaSsrO3JldHVybiBzWzYraV09YSxpKysscy5zZXQobiw2K2kpLHMuc2V0KG5ldyBVaW50OEFycmF5KGUpLDYraStyKSxzLmJ1ZmZlcn1uYXZpZ2F0b3IudXNlckFnZW50LmluZGV4T2YoIlNhZmFyaSIpPi0xJiYtMT09PW5hdmlnYXRvci51c2VyQWdlbnQuaW5kZXhPZigiQ2hyb21lIikmJihzZWxmLm9ucnRjdHJhbnNmb3JtPW49Pntjb25zdCByPW4udHJhbnNmb3JtZXI7bGV0IG89W107ci5vcHRpb25zLnBvcnQub25tZXNzYWdlPWU9PntlLmRhdGEuc2VpJiZvLnB1c2goZS5kYXRhLnNlaSl9LHNlbGYucG9zdE1lc3NhZ2UoInN0YXJ0ZWQiKTtjb25zdCBhPXIucmVhZGFibGUuZ2V0UmVhZGVyKCkscz1yLndyaXRhYmxlLmdldFdyaXRlcigpOyJyeCI9PT1yLm9wdGlvbnMubmFtZT9mdW5jdGlvbiB0KG4pe2EucmVhZCgpLnRoZW4oKHI9PntpZighci5kb25lKXtpZihyLnZhbHVlIGluc3RhbmNlb2YgUlRDRW5jb2RlZFZpZGVvRnJhbWUpe2NvbnN0IHQ9ZShyLnZhbHVlKTt0JiZuLm9wdGlvbnMucG9ydC5wb3N0TWVzc2FnZSh7c2VpOnR9KX1zLndyaXRlKHIudmFsdWUpLG4ub3B0aW9ucy5wb3J0LnBvc3RNZXNzYWdlKHt0cmFuc2Zvcm1lZDohMH0pLHQobil9fSkpfShyKToidHgiPT09ci5vcHRpb25zLm5hbWUmJmZ1bmN0aW9uIGUobil7YS5yZWFkKCkudGhlbigocj0+e2lmKCFyLmRvbmUpe2lmKHIudmFsdWUgaW5zdGFuY2VvZiBSVENFbmNvZGVkVmlkZW9GcmFtZSl7Y29uc3QgZT1vLnNoaWZ0KCk7ZSYmKHIudmFsdWUuZGF0YT10KHIudmFsdWUuZGF0YSxlKSl9cy53cml0ZShyLnZhbHVlKSxuLm9wdGlvbnMucG9ydC5wb3N0TWVzc2FnZSh7dHJhbnNmb3JtZWQ6ITB9KSxlKG4pfX0pKX0ocil9LHNlbGYucG9zdE1lc3NhZ2UoInJlZ2lzdGVyZWQiKSk7Cg==\")],{type:\"text/javascript\"});return setTimeout((()=>dU.revokeObjectURL(e)),0),new Worker(dU.createObjectURL(e))}const uU=new Map;const hU=new Map;async function pU(e){if(!IA().supportWebRTCEncodedTransform)return void jC.warning(\"browser not support audio encoded transform\");if(hU.has(e))return;const t={track:e.track};if(Ag()){if(!e.createEncodedStreams)return void jC.warning(\"browser not support createEncodedStreams() API\");let n=null;try{n=e.createEncodedStreams()}catch(e){return void jC.error(\"create audio-encoded-streams error\",e&&e.message)}const r=new TransformStream({transform(n,r){t.controller||(t.controller=r),e.track&&e.track.id!==t.track.id&&(jC.debug(\"audio track changed: \".concat(t.track.id,\" => \").concat(e.track.id)),t.track.removeEventListener(\"ended\",i),t.track=e.track,t.track.addEventListener(\"ended\",i)),r.enqueue(n)}});n.readable.pipeThrough(r).pipeTo(n.writable)}else if(bg()){if(\"undefined\"==typeof RTCRtpScriptTransform)return void jC.warning(\"browser not support RTCRtpScriptTransform\");const n=lU(),r=new MessageChannel;await new cg((e=>n.onmessage=t=>{\"registered\"===t.data&&e(void 0)}));const s=new RTCRtpScriptTransform(n,{name:\"rx\",port:r.port2},[r.port2]);e.transform=s,await new cg((e=>n.onmessage=t=>{\"started\"===t.data&&e(void 0)})),r.port1.onmessage=n=>{var r;n.data.transformed&&e.track&&(null===(r=e.track)||void 0===r?void 0:r.id)!==t.track.id&&(jC.debug(\"audio track changed: \".concat(t.track.id,\" => \").concat(e.track.id)),t.track.removeEventListener(\"ended\",i),t.track=e.track,t.track.addEventListener(\"ended\",i))},t.worker=n}function i(){e.track.removeEventListener(\"ended\",i),function(e){const t=hU.get(e);if(t){hU.delete(e);try{var i,n;null===(i=t.controller)||void 0===i||i.terminate(),null===(n=t.worker)||void 0===n||n.terminate()}catch(e){jC.warning(e&&e.message)}}}(e)}hU.set(e,t),e.track.addEventListener(\"ended\",i)}function _U(e){const t=new DataView(e.data);if(0===t.getUint8(0)&&0===t.getUint8(1)&&0===t.getUint8(2)&&1===t.getUint8(3)&&6===t.getUint8(4)){let i=6,n=0,r=0;for(;255===(r=t.getUint8(i++));)n+=255;n+=r;const s=function(e,t,i){let n=new Uint8Array(e,t,i),r=[],s=0;for(;s1&&void 0!==arguments[1]?arguments[1]:{};if(!IA().supportWebRTCEncodedTransform)return void jC.warning(\"browser not support video encoded transform\");if(!e.track)return;if(fU.has(e)){const i=fU.get(e);return void(i&&(i.onSei=t.onSei))}const i={track:e.track,onSei:t.onSei};if(Ag()){if(!e.createEncodedStreams)return void jC.warning(\"browser not support createEncodedStreams() API\");let t=null;try{t=e.createEncodedStreams()}catch(e){return void jC.error(\"create video-encoded-streams error\",e&&e.message)}const r=new TransformStream({transform(t,r){i.controller||(i.controller=r),e.track&&e.track.id!==i.track.id&&(jC.debug(\"video track changed: \".concat(i.track.id,\" => \").concat(e.track.id)),i.track.removeEventListener(\"ended\",n),i.track=e.track,i.track.addEventListener(\"ended\",n));const s=_U(t);s&&i.onSei&&i.onSei(s),r.enqueue(t)}});t.readable.pipeThrough(r).pipeTo(t.writable)}else if(bg()){if(\"undefined\"==typeof RTCRtpScriptTransform)return void jC.warning(\"browser not support RTCRtpScriptTransform\");const t=lU(),r=new MessageChannel;await new cg((e=>t.onmessage=t=>{\"registered\"===t.data&&e(void 0)}));const s=new RTCRtpScriptTransform(t,{name:\"rx\",port:r.port2},[r.port2]);e.transform=s,await new cg((e=>t.onmessage=t=>{\"started\"===t.data&&e(void 0)})),r.port1.onmessage=t=>{var r;t.data.transformed&&e.track&&(null===(r=e.track)||void 0===r?void 0:r.id)!==i.track.id?(jC.debug(\"video track changed: \".concat(i.track.id,\" => \").concat(e.track.id)),i.track.removeEventListener(\"ended\",n),i.track=e.track,i.track.addEventListener(\"ended\",n)):t.data.sei&&i.onSei&&i.onSei(t.data.sei)},i.worker=t}function n(){if(e.track){if(this.id!==e.track.id)return;e.track.removeEventListener(\"ended\",n)}!function(e){const t=fU.get(e);if(t){fU.delete(e);try{var i,n;null===(i=t.controller)||void 0===i||i.terminate(),null===(n=t.worker)||void 0===n||n.terminate()}catch(e){jC.warning(e&&e.message)}}}(e)}fU.set(e,i),e.track.addEventListener(\"ended\",n)}!function(){const e=Sg();CA.getDisplayMedia=function(e){if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)return!0;return!1}(),CA.getStreamFromExtension=e.name===Eg.CHROME&&Number(e.version)>34,CA.supportUnifiedPlan=function(){if(!window.RTCRtpTransceiver)return!1;if(!(\"currentDirection\"in RTCRtpTransceiver.prototype))return!1;const e=new RTCPeerConnection;let t=!1;try{e.addTransceiver(\"audio\"),t=!0}catch(e){}return e.close(),t}(),CA.supportMinBitrate=e.name===Eg.CHROME||e.name===Eg.EDGE,CA.supportSetRtpSenderParameters=function(){const e=Sg();if(!window.RTCRtpSender||!window.RTCRtpSender.prototype.setParameters||!window.RTCRtpSender.prototype.getParameters)return!1;return!!jg()||(!(!bg()&&!Ig())||e.name===Eg.FIREFOX&&Number(e.version)>=64)}(),e.name===Eg.SAFARI&&(Number(e.version)>=14?CA.supportDualStream=!0:CA.supportDualStream=!1),CA.webAudioMediaStreamDest=function(){const e=Sg();if(e.name===Eg.SAFARI&&Number(e.version)<12)return!1;return!0}(),CA.supportReplaceTrack=function(){if(!window.RTCRtpSender)return!1;if(\"function\"==typeof RTCRtpSender.prototype.replaceTrack)return!0;return!1}(),CA.supportWebGL=\"undefined\"!=typeof WebGLRenderingContext,CA.supportRequestFrame=!!window.CanvasCaptureMediaStreamTrack,jg()||(CA.webAudioWithAEC=!0),CA.supportShareAudio=function(){const e=Sg();if((e.os===_g.WIN_10||e.os===_g.WIN_81||e.os===_g.WIN_7||e.os===_g.LINUX||e.os===_g.MAC_OS||e.os===_g.CHROMIUM_OS)&&e.name===Eg.CHROME&&Number(e.version)>=74)return!0;return!1}(),CA.supportDataChannel=function(){if(Ng(76)||function(e){const t=Sg();return!(t.name!==Eg.FIREFOX||!t.osVersion)&&Number(t.version)>=e}(68)||function(e){const t=Sg();return!(t.name!==Eg.SAFARI||!t.osVersion)&&Number(t.version)>=e}(14))return!0;return!1}(),CA.supportPCSetConfiguration=function(){const e=window.RTCPeerConnection;return!wg()&&!!e&&e.prototype.setConfiguration instanceof Function}(),CA.supportWebRTCEncodedTransform=function(){const e=Sg();return\"Chrome\"===e.name&&Number(e.version)>=86||\"Safari\"===e.name&&Number(e.version)>=15}(),CA.supportWebRTCInsertableStream=function(){const e=Sg();return(e.name===Eg.CHROME||e.name===Eg.EDGE)&&Number(e.version)>=94&&\"MediaStreamTrackGenerator\"in window&&\"MediaStreamTrackProcessor\"in window}(),KT((()=>{CA.supportDualStreamEncoding=function(){const e=Sg();if(RC(\"DISABLE_WEBAUDIO\"))return!0;return\"Safari\"===e.name&&Number(e.version)>=14||!!(\"Chrome\"===e.name&&/Windows/i.test(e.os||\"\")&&Number(e.version)>=100&&RC(\"CHROME_DUAL_STREAM_USE_ENCODING\"))}(),jC.info(\"browser compatibility\",JSON.stringify(CA),JSON.stringify(e))}))}();class TU extends dT{constructor(){super(...arguments),sh(this,\"resultStorage\",new Map)}setLocalAudioStats(e,t,i){this.record(\"AUDIO_INPUT_LEVEL_TOO_LOW\",e,this.checkAudioInputLevel(i,t)),this.record(\"SEND_AUDIO_BITRATE_TOO_LOW\",e,this.checkSendAudioBitrate(i,t))}setLocalVideoStats(e,t,i){this.record(\"SEND_VIDEO_BITRATE_TOO_LOW\",e,this.checkSendVideoBitrate(i,t)),this.record(\"FRAMERATE_INPUT_TOO_LOW\",e,this.checkFramerateInput(i,t)),this.record(\"FRAMERATE_SENT_TOO_LOW\",e,this.checkFramerateSent(i))}setRemoteAudioStats(e,t){const i=e.getUserId();this.record(\"AUDIO_OUTPUT_LEVEL_TOO_LOW\",i,this.checkAudioOutputLevel(t))}setRemoteVideoStats(e,t){const i=e.getUserId();this.record(\"RECV_VIDEO_DECODE_FAILED\",i,this.checkVideoDecode(t))}record(e,t,i){if(RC(\"STATS_UPDATE_INTERVAL\")>500)return;this.resultStorage.has(e)||this.resultStorage.set(e,{result:[],isPrevNormal:!0});const n=this.resultStorage.get(e);if(n&&(n.result.push(i),n.result.length>=5)){var r;const i=bn(r=n.result).call(r,!0);n.isPrevNormal&&!i&&this.emit(\"exception\",SU[e],e,t),!n.isPrevNormal&&i&&this.emit(\"exception\",SU[e]+2e3,e+\"_RECOVER\",t),n.isPrevNormal=i,n.result=[]}}checkAudioOutputLevel(e){return!(e.receiveBitrate>0&&0===e.receiveLevel)}checkAudioInputLevel(e,t){return t instanceof nw&&!t.isActive||(!!t.muted||0!==e.sendVolumeLevel)}checkFramerateInput(e,t){let i=null;t._encoderConfig&&t._encoderConfig.frameRate&&(i=Sy(t._encoderConfig.frameRate));const n=e.captureFrameRate;return!i||!n||!(i>10&&n<5||i<10&&i>=5&&n<=1)}checkFramerateSent(e){return!(e.captureFrameRate&&e.sendFrameRate&&e.captureFrameRate>5&&e.sendFrameRate<=1)}checkSendVideoBitrate(e,t){return!!t.muted||0!==e.sendBitrate}checkSendAudioBitrate(e,t){return t instanceof nw&&!t.isActive||(!!t.muted||0!==e.sendBitrate)}checkVideoDecode(e){return 0===e.receiveBitrate||0!==e.decodeFrameRate}}const SU={FRAMERATE_INPUT_TOO_LOW:1001,FRAMERATE_SENT_TOO_LOW:1002,SEND_VIDEO_BITRATE_TOO_LOW:1003,RECV_VIDEO_DECODE_FAILED:1005,AUDIO_INPUT_LEVEL_TOO_LOW:2001,AUDIO_OUTPUT_LEVEL_TOO_LOW:2002,SEND_AUDIO_BITRATE_TOO_LOW:2003};const RU=new class{markSubscribeStart(e,t){performance.mark(\"agora-web-sdk/\".concat(e,\"/subscribe-\").concat(t))}markPublishStart(e,t){performance.mark(\"agora-web-sdk/\".concat(e,\"/publish-\").concat(t))}measureFromSubscribeStart(e,t){const i=performance.getEntriesByName(\"agora-web-sdk/\".concat(e,\"/subscribe-\").concat(t));if(i.length>0){const e=i[i.length-1];return Math.round(performance.now()-e.startTime)}return 0}measureFromPublishStart(e,t){const i=performance.getEntriesByName(\"agora-web-sdk/\".concat(e,\"/publish-\").concat(t));if(i.length>0){const e=i[i.length-1];return Math.round(performance.now()-e.startTime)}return 0}};function CU(e,t){this.v=e,this.k=t}function IU(e){return new CU(e,0)}var vU=ag,yU=um;wi({target:\"Promise\",stat:!0,forced:!0},{withResolvers:function(){var e=yU.f(this);return{promise:e.promise,resolve:e.resolve,reject:e.reject}}});var AU=um,bU=YE;wi({target:\"Promise\",stat:!0,forced:!0},{try:function(e){var t=AU.f(this),i=bU(e);return(i.error?t.reject:t.resolve)(i.value),t.promise}});var wU=i(vU),OU=Fo.f(\"asyncIterator\"),NU=i(OU);function DU(e){var t,i;function n(t,i){try{var s=e[t](i),o=s.value,a=o instanceof CU;wU.resolve(a?o.v:o).then((function(i){if(a){var c=\"return\"===t?\"return\":\"next\";if(!o.k||i.done)return n(c,i);i=e[c](i).value}r(s.done?\"return\":\"normal\",i)}),(function(e){n(\"throw\",e)}))}catch(e){r(\"throw\",e)}}function r(e,r){switch(e){case\"return\":t.resolve({value:r,done:!0});break;case\"throw\":t.reject(r);break;default:t.resolve({value:r,done:!1})}(t=t.next)?n(t.key,t.arg):i=null}this._invoke=function(e,r){return new wU((function(s,o){var a={key:e,arg:r,resolve:s,reject:o,next:null};i?i=i.next=a:(t=i=a,n(e,r))}))},\"function\"!=typeof e.return&&(this.return=void 0)}function PU(e){return function(){return new DU(e.apply(this,arguments))}}DU.prototype[\"function\"==typeof xu&&NU||\"@@asyncIterator\"]=function(){return this},DU.prototype.next=function(e){return this._invoke(\"next\",e)},DU.prototype.throw=function(e){return this._invoke(\"throw\",e)},DU.prototype.return=function(e){return this._invoke(\"return\",e)};var LU=i(ie.Object.getOwnPropertySymbols),kU=wi,MU=Ki.indexOf,UU=Ih,xU=v([].indexOf),VU=!!xU&&1/xU([1],1,-0)<0;kU({target:\"Array\",proto:!0,forced:VU||!UU(\"indexOf\")},{indexOf:function(e){var t=arguments.length>1?arguments[1]:void 0;return VU?xU(this,e,t)||0:MU(this,e,t)}});var FU=zi(\"Array\").indexOf,BU=l,jU=FU,GU=Array.prototype,WU=i((function(e){var t=e.indexOf;return e===GU||BU(GU,e)&&t===GU.indexOf?jU:t})),HU=Je,KU=Ys;wi({target:\"Object\",stat:!0,forced:n((function(){KU(1)}))},{keys:function(e){return KU(HU(e))}});var YU=i(ie.Object.keys);function qU(e,t){if(null==e)return{};var i,n,r=function(e,t){if(null==e)return{};var i,n,r={},s=YU(e);for(n=0;n=0||(r[i]=e[i]);return r}(e,t);if(LU){var s=LU(e);for(n=0;n=0||Object.prototype.propertyIsEnumerable.call(e,i)&&(r[i]=e[i])}return r}var zU={exports:{}};!function(e,t){e.exports=(()=>{var e={8:(e,t,i)=>{i.r(t),i.d(t,{Parser:()=>C,Printer:()=>b,parse:()=>D,print:()=>P});const n=\"\\n\",r=\"\".concat(\"\\r\").concat(n),s=\" \";let o;function a(e){return e>=\"0\"&&e<=\"9\"}function c(e){return e>=\"!\"&&e<=\"~\"}function d(e){return c(e)||e>=\"\u0080\"&&e<=\"\u00FF\"}function l(e){return\"!\"===e||e>=\"#\"&&e<=\"'\"||e>=\"*\"&&e<=\"+\"||e>=\"-\"&&e<=\".\"||e>=\"0\"&&e<=\"9\"||e>=\"A\"&&e<=\"Z\"||e>=\"^\"&&e<=\"~\"}function u(e){return e>=\"1\"&&e<=\"9\"}function h(e){return e>=\"A\"&&e<=\"Z\"||e>=\"a\"&&e<=\"z\"}function p(e){return\"d\"===e||\"h\"===e||\"m\"===e||\"s\"===e}function _(e){return e>\"\u0001\"&&e<\"\\t\"||e>\"\\v\"&&e<\"\\f\"||e>\"\u000E\"&&e<\"\u00FF\"}function E(e){return h(e)||a(e)||\"+\"===e||\"/\"===e}function m(e){return a(e)||h(e)||\"+\"===e||\"/\"===e||\"-\"===e||\"_\"===e}function f(e){return h(e)||a(e)||\"+\"===e||\"/\"===e}function g(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function T(e){for(var t=1;t=0&&n<=255)return i;throw new Error(\"Invalid decimal uchar\")}consumeIP6Address(e,t){let i=this.consumeHexpart(e,t);return\":\"===e[i]?(i+=1,i=this.consumeIP4Address(e,i),i):i}consumeHexpart(e,t){let i=t;if(\":\"===e[i]&&\":\"===e[i+1]){i+=2;try{i=this.consumeHexseq(e,i)}catch(e){}return i}if(i=this.consumeHexseq(e,i),\":\"===e[i]&&\":\"===e[i+1]){i+=2;try{i=this.consumeHexseq(e,i)}catch(e){}return i}return i}consumeHexseq(e,t){let i=t;for(;i=this.consumeHex4(e,i),\":\"===e[i]&&\":\"!==e[i+1];)i+=1;return i}consumeHex4(e,t){let i=0;for(;i<4;i++)if(!((n=e[t+i])>=\"0\"&&n<=\"9\"||n>=\"a\"&&n<=\"f\"||n>=\"A\"&&n<=\"F\")){if(0===i)throw new Error(\"Invalid hex 4\");break}var n;return t+i}consumeFQDN(e,t){let i=t;for(;a(e[i])||h(e[i])||\"-\"===e[i]||\".\"===e[i];)i+=1;if(i-t<4)throw new Error(\"Invalid FQDN\");return i}consumeExtnAddr(e,t){return this.consumeOneOrMore(e,t,d)}consumeMulticastAddress(e,t,i){switch(i){case\"IP4\":case\"ip4\":return this.consumeIP4MulticastAddress(e,t);case\"IP6\":case\"ip6\":return this.consumeIP6MulticastAddress(e,t);default:try{return this.consumeFQDN(e,t)}catch(i){return this.consumeExtnAddr(e,t)}}}consumeIP6MulticastAddress(e,t){const i=this.consumeHexpart(e,t);return\"/\"===e[i]?this.consumeInteger(e,i+1):i}consumeIP4MulticastAddress(e,t){let i=t+3;const n=e.slice(t,i),r=parseInt(n);if(r<224||r>239)throw new Error(\"Invalid IP4 multicast address, IPv4 multicast addresses may be in the range 224.0.0.0 to 239.255.255.255.\");for(let t=0;t<3;t++){if(\".\"!==e[i])throw new Error(\"Invalid IP4 multicast address.\");i+=1,i=this.consumeDecimalUChar(e,i)}return\"/\"===e[i]&&(i+=1),i=this.consumeTTL(e,i),\"/\"===e[i]&&(i=this.consumeInteger(e,i)),i}consumeInteger(e,t){if(!u(e[t]))throw new Error(\"Invalid integer.\");for(t+=1;a(e[t]);)t+=1;return t}consumeTTL(e,t){if(\"0\"===e[t])return t+1;if(!u(e[t]))throw new Error(\"Invalid TTL.\");t+=1;for(let i=0;i<2&&a(e[t]);i++)t+=1;return t}consumeToken(e,t){return this.consumeOneOrMore(e,t,l)}consumeTime(e,t){let i=t;if(\"0\"===e[i])return i+1;for(u(e[i])&&(i+=1);a(e[i]);)i++;if(i-t<10)throw new Error(\"Invalid time\");return i}consumeAddress(e,t){return this.consumeTill(e,t,s)}consumeTypedTime(e,t){let i=t;return i=this.consumeOneOrMore(e,i,a),p(e[i])?i+1:i}consumeRepeatInterval(e,t){if(!u(e[t]))throw new Error(\"Invalid repeat interval\");for(t+=1;a(e[t]);)t+=1;return p(e[t])&&(t+=1),t}consumePort(e,t){return this.consumeOneOrMore(e,t,a)}consume(e,t,i){for(let n=0;n=e.length)throw new Error(\"consume exceeding value length\");if(e[t+n]!==i[n])throw new Error(\"consume \".concat(i,\" failed at \").concat(n))}return t+i.length}consumeTill(e,t,i){let n=t;for(;n!!e.trim())).map(this.parseLine),this.currentLine=0;const i=this.parseVersion(),n=this.parseOrigin(),r=this.parseSessionName(),s=this.parseInformation(),o=this.parseUri(),a=this.parseEmail(),c=this.parsePhone(),d=this.parseConnection(),l=this.parseBandWidth(),u=this.parseTimeFields(),h=this.parseKey(),p=this.parseSessionAttribute(),_=this.parseMediaDescription();if(this.currentLine!==this.records.length)throw new Error(\"parsing failed, non exhaustive sdp lines.\");return{version:i,origin:n,sessionName:r,information:s,uri:o,emails:a,phones:c,connection:d,bandwidths:l,timeFields:u,key:h,attributes:p,mediaDescriptions:_}}getCurrentRecord(){const e=this.records[this.currentLine];if(!e)throw new Error(\"Record doesn't exit.\");return e}probeEOL(e){for(let t=0;t=.\");const i=e[0];if(\"=\"!==e[1])throw new Error('Invalid sdp line, should be a single character followed by an \"=\" sign.');return{type:i,value:e.slice(2),line:t,cur:0}}parseSessionAttribute(){const e=new v;for(;this.currentLinel(e)&&\":\"!==e)),_cur:0};\":\"===t.value[t.cur]&&(t.cur+=1,i.attValue=this.extractOneOrMore(t,_)),e.parse(i),this.currentLine++}return e.digest()}parseMediaAttributes(e){const t=new y(e);for(;this.currentLinel(e)&&\":\"!==e)),_cur:0};\":\"===e.value[e.cur]&&(e.cur+=1,i.attValue=this.extractOneOrMore(e,_)),t.parse(i),this.currentLine++}return t.digest()}parseKey(){const e=this.getCurrentRecord();if(e.type===o.KEY){if(\"prompt\"===e.value||\"clear:\"===e.value||\"base64:\"===e.value||\"uri:\"===e.value)return e.value;throw this.currentLine++,new Error(\"Invalid key.\")}}parseZone(){const e=this.getCurrentRecord();if(e.type===o.ZONE_ADJUSTMENTS){const t=[];for(;;)try{const i=this.extract(e,this.consumeTime);this.consumeSpaceForRecord(e);let n=!1;\"-\"===e.value[e.cur]&&(n=!0,e.cur+=1);const r=this.extract(e,this.consumeTypedTime);t.push({time:i,typedTime:r,back:n})}catch(e){break}if(0===t.length)throw new Error(\"Invalid zone adjustments\");return this.currentLine++,t}return[]}parseRepeat(){const e=[];for(;;){const t=this.getCurrentRecord();if(t.type!==o.REPEAT)break;{const i=this.extract(t,this.consumeRepeatInterval),n=this.parseTypedTime(t);e.push({repeatInterval:i,typedTimes:n}),this.currentLine++}}return e}parseTypedTime(e){const t=[];for(;;)try{this.consumeSpaceForRecord(e),t.push(this.extract(e,this.consumeTypedTime))}catch(e){break}if(0===t.length)throw new Error(\"Invalid typed time.\");return t}parseTime(){const e=this.getCurrentRecord(),t=this.extract(e,this.consumeTime);this.consumeSpaceForRecord(e);const i=this.extract(e,this.consumeTime);return this.currentLine++,{startTime:t,stopTime:i}}parseBandWidth(){const e=[];for(;this.currentLineo)throw new Error(\"error in length, should be less or equal than \".concat(o,\" characters.\"));return e._cur=n,r}consumeAttributeSpace(e){if(e.attValue[e._cur]!==s)throw new Error(\"Invalid space at \".concat(e._cur,\".\"));e._cur+=1}extract(e,t,...i){if(!e.attValue)throw new Error(\"Nothing to extract from attValue.\");const n=t.call(this,e.attValue,e._cur,...i),r=e.attValue.slice(e._cur,n);return e._cur=n,r}atEnd(e){if(!e.attValue)throw new Error;return e._cur>=e.attValue.length}peekChar(e){if(!e.attValue)throw new Error;return e.attValue[e._cur]}peek(e,t){if(!e.attValue)throw new Error;for(let i=0;ie!==s&&_(e)));i.push({name:t,value:n})}this.attributes.identities.push({assertionValue:t,extensions:i})}parseMsidSemantic(e){this.peekChar(e)===s&&this.consumeAttributeSpace(e);const t={semantic:this.extract(e,this.consumeToken),identifierList:[]};for(;;){try{this.consumeAttributeSpace(e)}catch(e){break}if(\"*\"===this.peekChar(e)){this.extract(e,this.consume,\"*\"),t.applyForAll=!0;break}{const i=this.extract(e,this.consumeTill,s);t.identifierList.push(i)}}this.attributes.msidSemantic=t}}class y extends I{constructor(e){super(),S(this,\"attributes\",void 0),-1!==e.protos.indexOf(\"RTP\")||e.protos.indexOf(\"rtp\"),this.attributes={unrecognized:[],candidates:[],extmaps:[],fingerprints:[],imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:[],ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:[]}}parse(e){if(this.digested)throw new Error(\"already digested\");try{switch(e.attField){case\"extmap\":this.parseExtmap(e);break;case\"setup\":this.parseSetup(e);break;case\"ice-ufrag\":this.parseIceUfrag(e);break;case\"ice-pwd\":this.parseIcePwd(e);break;case\"ice-options\":this.parseIceOptions(e);break;case\"candidate\":this.parseCandidate(e);break;case\"remote-candidate\":this.parseRemoteCandidate(e);break;case\"end-of-candidates\":this.parseEndOfCandidates();break;case\"fingerprint\":this.parseFingerprint(e);break;case\"rtpmap\":this.parseRtpmap(e);break;case\"ptime\":this.parsePtime(e);break;case\"maxptime\":this.parseMaxPtime(e);break;case\"sendrecv\":case\"recvonly\":case\"sendonly\":case\"inactive\":this.parseDirection(e);break;case\"ssrc\":this.parseSSRC(e);break;case\"fmtp\":this.parseFmtp(e);break;case\"rtcp-fb\":this.parseRtcpFb(e);break;case\"rtcp-mux\":this.parseRTCPMux();break;case\"rtcp-mux-only\":this.parseRTCPMuxOnly();break;case\"rtcp-rsize\":this.parseRTCPRsize();break;case\"rtcp\":this.parseRTCP(e);break;case\"mid\":this.parseMid(e);break;case\"msid\":this.parseMsid(e);break;case\"imageattr\":this.parseImageAttr(e);break;case\"rid\":this.parseRid(e);break;case\"simulcast\":this.parseSimulcast(e);break;case\"sctp-port\":this.parseSctpPort(e);break;case\"max-message-size\":this.parseMaxMessageSize(e);break;case\"ssrc-group\":this.parseSSRCGroup(e);break;default:e.ignored=!0,this.attributes.unrecognized.push(e)}}catch(t){throw console.error(\"parsing media attribute \".concat(e.attField,' error, \"a=').concat(e.attField,\":\").concat(e.attValue,'\"')),t}if(!e.ignored&&e.attValue&&!this.atEnd(e))throw new Error(\"attribute parsing error\")}parseCandidate(e){const t=this.extractOneOrMore(e,E,[1,32]);this.consumeAttributeSpace(e);const i=this.extractOneOrMore(e,a,[1,5]);this.consumeAttributeSpace(e);const n=this.extract(e,this.consumeToken);this.consumeAttributeSpace(e);const r=this.extractOneOrMore(e,a,[1,10]);this.consumeAttributeSpace(e);const o=this.extract(e,this.consumeAddress);this.consumeAttributeSpace(e);const d=this.extract(e,this.consumePort);this.consumeAttributeSpace(e),this.extract(e,this.consume,\"typ\"),this.consumeAttributeSpace(e);const l={foundation:t,componentId:i,transport:n,priority:r,connectionAddress:o,port:d,type:this.extract(e,this.consumeToken),extension:{}};for(this.peek(e,\" raddr\")&&(this.extract(e,this.consume,\" raddr\"),this.consumeAttributeSpace(e),l.relAddr=this.extract(e,this.consumeAddress)),this.peek(e,\" rport\")&&(this.extract(e,this.consume,\" rport\"),this.consumeAttributeSpace(e),l.relPort=this.extract(e,this.consumePort));this.peekChar(e)===s;){this.consumeAttributeSpace(e);const t=this.extract(e,this.consumeToken);this.consumeAttributeSpace(e),l.extension[t]=this.extractOneOrMore(e,c)}this.attributes.candidates.push(l)}parseRemoteCandidate(e){const t=[];for(;;){const i=this.extractOneOrMore(e,a,[1,5]);this.consumeAttributeSpace(e);const n=this.extract(e,this.consumeAddress);this.consumeAttributeSpace(e);const r=this.extract(e,this.consumePort);t.push({componentId:i,connectionAddress:n,port:r});try{this.consumeAttributeSpace(e)}catch(e){break}}this.attributes.remoteCandidatesList.push(t)}parseEndOfCandidates(){if(this.attributes.endOfCandidates)throw new Error(\"must be only one line of end-of-candidates\");this.attributes.endOfCandidates=!0}parseRtpmap(e){const t=this.extract(e,this.consumeToken);this.consumeAttributeSpace(e);const i=this.extract(e,this.consumeTill,\"/\");this.extract(e,this.consume,\"/\");const n={encodingName:i,clockRate:this.extractOneOrMore(e,a)};this.atEnd(e)||\"/\"!==this.peekChar(e)||(this.extract(e,this.consume,\"/\"),n.encodingParameters=parseInt(this.extract(e,this.consumeTill),10));const r=this.attributes.payloads.find((e=>e.payloadType===parseInt(t,10)));r?r.rtpMap=n:this.attributes.payloads.push({payloadType:parseInt(t,10),rtpMap:n,rtcpFeedbacks:[]})}parsePtime(e){if(this.attributes.ptime)throw new Error(\"must be only one line of ptime\");this.attributes.ptime=this.extract(e,this.consumeTill)}parseMaxPtime(e){if(this.attributes.maxPtime)throw new Error(\"must be only one line of ptime\");this.attributes.maxPtime=this.extract(e,this.consumeTill)}parseDirection(e){if(this.attributes.direction)throw new Error(\"must be only one line of direction info\");this.attributes.direction=e.attField}parseSSRC(e){const t=this.extractOneOrMore(e,a);this.consumeAttributeSpace(e);const i=this.extract(e,this.consumeTill,\":\");let n;\":\"===this.peekChar(e)&&(this.extract(e,this.consume,\":\"),n=this.extract(e,this.consumeTill));const r=this.attributes.ssrcs.find((e=>e.ssrcId===parseInt(t,10)));r?r.attributes[i]=n:this.attributes.ssrcs.push({ssrcId:parseInt(t,10),attributes:{[i]:n}})}parseFmtp(e){const t=this.extract(e,this.consumeTill,s);this.consumeAttributeSpace(e);const i=this.extract(e,this.consumeTill),n={};i.split(\";\").forEach((e=>{let[t,i]=e.split(\"=\");t=t.trim();const r=\"string\"==typeof i?i.trim():null;\"string\"==typeof t&&t.length>0&&(n[t]=r)}));const r=this.attributes.payloads.find((e=>e.payloadType===parseInt(t,10)));r?r.fmtp={parameters:n}:this.attributes.payloads.push({payloadType:parseInt(t,10),rtcpFeedbacks:[],fmtp:{parameters:n}})}parseFmtParameters(e){const t={},i=this.extract(e,this.consumeTill,\"=\");e._cur++;const n=this.extract(e,this.consumeTill,\";\");for(t[i]=n;\";\"===e.attValue[e._cur];){const i=this.extract(e,this.consumeTill,\"=\");e._cur++;const n=this.extract(e,this.consumeTill,\";\");t[i]=n}return t}parseRtcpFb(e){let t=\"\";t=\"*\"===this.peekChar(e)?this.extract(e,this.consume,\"*\"):this.extract(e,this.consumeTill,s),this.consumeAttributeSpace(e);const i=this.extract(e,this.consumeTill,s);let n;if(\"trr-int\"===i)n={type:i,interval:this.extract(e,this.consumeTill)};else{const t={type:i};this.peekChar(e)===s&&(this.consumeAttributeSpace(e),t.parameter=this.extract(e,this.consumeToken),this.peekChar(e)===s&&(t.additional=this.extract(e,this.consumeTill))),n=t}if(\"*\"===t)this.attributes.rtcpFeedbackWildcards.push(n);else{const e=this.attributes.payloads.find((e=>e.payloadType===parseInt(t,10)));e?e.rtcpFeedbacks.push(n):this.attributes.payloads.push({payloadType:parseInt(t,10),rtcpFeedbacks:[n]})}}parseRTCPMux(){if(this.attributes.rtcpMux)throw new Error(\"must be single line of rtcp-mux\");this.attributes.rtcpMux=!0}parseRTCPMuxOnly(){if(this.attributes.rtcpMuxOnly)throw new Error(\"must be single line of rtcp-only\");this.attributes.rtcpMuxOnly=!0}parseRTCPRsize(){if(this.attributes.rtcpRsize)throw new Error(\"must be single line of rtcp-rsize\");this.attributes.rtcpRsize=!0}parseRTCP(e){if(this.attributes.rtcp)throw new Error(\"must be single line of rtcp\");const t={port:this.extract(e,this.consumePort)};this.peekChar(e)===s&&(this.consumeAttributeSpace(e),t.netType=this.extractOneOrMore(e,l),this.consumeAttributeSpace(e),t.addressType=this.extractOneOrMore(e,l),this.consumeAttributeSpace(e),t.address=this.extract(e,this.consumeAddress)),this.attributes.rtcp=t}parseMsid(e){const t={id:this.extractOneOrMore(e,l,[1,64])};this.peekChar(e)===s&&(this.consumeAttributeSpace(e),t.appdata=this.extractOneOrMore(e,l,[1,64])),this.attributes.msids.push(t)}parseImageAttr(e){this.attributes.imageattr.push(e.attValue)}parseRid(e){const t=this.extractOneOrMore(e,(e=>h(e)||a(e)||\"_\"===e||\"-\"===e));this.consumeAttributeSpace(e);const i={id:t,direction:this.extract(e,this.consumeToken),params:[]};if(this.peekChar(e)===s){if(this.consumeAttributeSpace(e),this.peek(e,\"pt=\")){this.extract(e,this.consume,\"pt=\");const t=[];for(;;){const i=this.extract(e,this.consumeToken);t.push(i);try{this.extract(e,this.consume,\",\")}catch(e){break}}i.payloads=t,this.peekChar(e)===s&&this.extract(e,this.consume,s)}for(;;){const t=this.extract(e,this.consumeToken);switch(t){case\"depend\":{const n={type:t,rids:this.extract(e,this.consume,\"=\").split(\",\")};i.params.push(n);break}default:{const n={type:t};\"=\"===this.peekChar(e)&&(this.extract(e,this.consume,\"=\"),n.val=this.extract(e,this.consumeTill,\";\")),i.params.push(n)}}try{this.extract(e,this.consume,\";\")}catch(e){break}}}this.attributes.rids.push(i)}parseSimulcast(e){if(this.attributes.simulcast)throw new Error(\"must be single line of simulcast\");this.attributes.simulcast=e.attValue,this.extract(e,this.consumeTill)}parseSctpPort(e){this.attributes.sctpPort=this.extractOneOrMore(e,a,[1,5])}parseMaxMessageSize(e){this.attributes.maxMessageSize=this.extractOneOrMore(e,a,[1,void 0])}digest(){return this.digested=!0,this.attributes}parseMid(e){this.attributes.mid=this.extract(e,this.consumeToken)}parseSSRCGroup(e){const t=this.extract(e,this.consumeToken),i=[];for(;;)try{this.consumeAttributeSpace(e);const t=this.extract(e,this.consumeInteger);i.push(parseInt(t,10))}catch(e){break}this.attributes.ssrcGroups.push({semantic:t,ssrcIds:i})}}function A(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}class b{constructor(){A(this,\"eol\",r)}print(e,t){let i=\"\";return t&&(this.eol=t),i+=this.printVersion(e.version),i+=this.printOrigin(e.origin),i+=this.printSessionName(e.sessionName),i+=this.printInformation(e.information),i+=this.printUri(e.uri),i+=this.printEmail(e.emails),i+=this.printPhone(e.phones),i+=this.printConnection(e.connection),i+=this.printBandwidth(e.bandwidths),i+=this.printTimeFields(e.timeFields),i+=this.printKey(e.key),i+=this.printSessionAttributes(e.attributes),i+=this.printMediaDescription(e.mediaDescriptions),i}printVersion(e){return\"v=\".concat(e).concat(this.eol)}printOrigin(e){return\"o=\".concat(e.username,\" \").concat(e.sessId,\" \").concat(e.sessVersion,\" \").concat(e.nettype,\" \").concat(e.addrtype,\" \").concat(e.unicastAddress).concat(this.eol)}printSessionName(e){return e?\"s=\".concat(e).concat(this.eol):\"\"}printInformation(e){return e?\"i=\".concat(e).concat(this.eol):\"\"}printUri(e){return e?\"u=\".concat(e).concat(this.eol):\"\"}printEmail(e){let t=\"\";for(const i of e)t+=\"e=\".concat(i).concat(this.eol);return t}printPhone(e){let t=\"\";for(const i of e)t+=\"e=\".concat(i).concat(this.eol);return t}printConnection(e){return e?\"c=\".concat(e.nettype,\" \").concat(e.addrtype,\" \").concat(e.address).concat(this.eol):\"\"}printBandwidth(e){let t=\"\";for(const i of e)t+=\"b=\".concat(i.bwtype,\":\").concat(i.bandwidth).concat(this.eol);return t}printTimeFields(e){let t=\"\";for(const i of e){t+=\"t=\".concat(i.time.startTime,\" \").concat(i.time.startTime).concat(this.eol);for(const e of i.repeats)t+=\"r=\".concat(e.repeatInterval,\" \").concat(e.typedTimes.join(\" \")).concat(this.eol);i.zoneAdjustments&&(t+=\"z=\",t+=\"z=\".concat(i.zoneAdjustments.map((e=>\"\".concat(e.time,\" \").concat(e.back?\"-\":\"\",\" \").concat(e.typedTime))).join(\" \")).concat(this.eol),t+=this.eol)}return t}printKey(e){return e?\"k=\".concat(e).concat(this.eol):\"\"}printAttributes(e){let t=\"\";for(const i of e)t+=\"a=\".concat(i.attField).concat(i.attValue?\":\".concat(i.attValue):\"\").concat(this.eol);return t}printMediaDescription(e){let t=\"\";for(const i of e)t+=this.printMedia(i.media),t+=this.printInformation(i.information),t+=this.printConnections(i.connections),t+=this.printBandwidth(i.bandwidths),t+=this.printKey(i.key),t+=this.printMediaAttributes(i);return t}printConnections(e){let t=\"\";for(const i of e)t+=this.printConnection(i);return t}printMedia(e){return\"m=\".concat(e.mediaType,\" \").concat(e.port,\" \").concat(e.protos.join(\"/\"),\" \").concat(e.fmts.join(\" \")).concat(this.eol)}printSessionAttributes(e){return new O(this.eol).print(e)}printMediaAttributes(e){return new N(this.eol).print(e)}}class w{constructor(e){A(this,\"eol\",void 0),this.eol=e}printIceUfrag(e){return void 0===e?\"\":\"a=ice-ufrag:\".concat(e).concat(this.eol)}printIcePwd(e){return void 0===e?\"\":\"a=ice-pwd:\".concat(e).concat(this.eol)}printIceOptions(e){return void 0===e?\"\":\"a=ice-options:\".concat(e.join(s)).concat(this.eol)}printFingerprints(e){return e.length>0?e.map((e=>\"a=fingerprint:\".concat(e.hashFunction).concat(s).concat(e.fingerprint))).join(this.eol)+this.eol:\"\"}printExtmap(e){return e.map((e=>\"a=extmap:\".concat(e.entry).concat(e.direction?\"/\".concat(e.direction):\"\").concat(s).concat(e.extensionName).concat(e.extensionAttributes?\"\".concat(s).concat(e.extensionAttributes):\"\").concat(this.eol))).join(\"\")}printSetup(e){return void 0===e?\"\":\"a=setup:\".concat(e).concat(this.eol)}printUnrecognized(e){return e.map((e=>\"a=\".concat(e.attField).concat(e.attValue?\":\".concat(e.attValue):\"\").concat(this.eol))).join(\"\")}}class O extends w{print(e){let t=\"\";return t+=this.printGroups(e.groups),t+=this.printMsidSemantic(e.msidSemantic),t+=this.printIceLite(e.iceLite),t+=this.printIceUfrag(e.iceUfrag),t+=this.printIcePwd(e.icePwd),t+=this.printIceOptions(e.iceOptions),t+=this.printFingerprints(e.fingerprints),t+=this.printSetup(e.setup),t+=this.printTlsId(e.tlsId),t+=this.printIdentity(e.identities),t+=this.printExtmap(e.extmaps),t+=this.printUnrecognized(e.unrecognized),t}printGroups(e){let t=\"\";return e.length>0&&(t+=e.map((e=>\"a=group:\".concat(e.semantic).concat(e.identificationTag.map((e=>\"\".concat(s).concat(e))).join(\"\")).concat(this.eol))).join(\"\")),t}printIceLite(e){return void 0===e?\"\":\"a=ice-lite\"+this.eol}printTlsId(e){return e?\"a=tls-id:\".concat(e).concat(this.eol):\"\"}printIdentity(e){return 0===e.length?\"\":e.map((e=>\"a=identity:\".concat(e.assertionValue).concat(e.extensions.map((e=>\"\".concat(s).concat(e.name).concat(e.value?\"=\".concat(e.value):\"\")))))).join(this.eol)+this.eol}printMsidSemantic(e){if(!e)return\"\";let t=\"a=msid-semantic:\".concat(e.semantic);return e.applyForAll?t+=\"\".concat(s,\"*\"):e.identifierList.length>0&&(t+=e.identifierList.map((e=>\"\".concat(s).concat(e)))),t+this.eol}}class N extends w{print(e){const t=e.attributes;let i=\"\";return i+=this.printRTCP(t.rtcp),i+=this.printIceUfrag(t.iceUfrag),i+=this.printIcePwd(t.icePwd),i+=this.printIceOptions(t.iceOptions),i+=this.printCandidates(t.candidates),i+=this.printRemoteCandidatesList(t.remoteCandidatesList),i+=this.printEndOfCandidates(t.endOfCandidates),i+=this.printFingerprints(t.fingerprints),i+=this.printSetup(t.setup),i+=this.printMid(t.mid),i+=this.printExtmap(t.extmaps),i+=this.printRTPRelated(t),i+=this.printPtime(t.ptime),i+=this.printMaxPtime(t.maxPtime),i+=this.printDirection(t.direction),i+=this.printSSRCGroups(t.ssrcGroups),i+=this.printSSRC(t.ssrcs),i+=this.printRTCPMux(t.rtcpMux),i+=this.printRTCPMuxOnly(t.rtcpMuxOnly),i+=this.printRTCPRsize(t.rtcpRsize),i+=this.printMSId(t.msids),i+=this.printImageattr(t.imageattr),i+=this.printRid(t.rids),i+=this.printSimulcast(t.simulcast),i+=this.printSCTPPort(t.sctpPort),i+=this.printMaxMessageSize(t.maxMessageSize),i+=this.printUnrecognized(t.unrecognized),i}printCandidates(e){return e.map((e=>\"a=candidate:\".concat(e.foundation).concat(s).concat(e.componentId).concat(s).concat(e.transport).concat(s).concat(e.priority).concat(s).concat(e.connectionAddress).concat(s).concat(e.port).concat(s,\"typ\").concat(s).concat(e.type).concat(e.relAddr?\"\".concat(s,\"raddr\").concat(s).concat(e.relAddr):\"\").concat(e.relPort?\"\".concat(s,\"rport\").concat(s).concat(e.relPort):\"\").concat(Object.keys(e.extension).map((t=>\"\".concat(s).concat(t).concat(s).concat(e.extension[t]))).join(\"\")).concat(this.eol))).join(\"\")}printRemoteCandidatesList(e){return e.map((e=>\"a=remote-candidates:\".concat(e.join(s)).concat(this.eol))).join(\"\")}printEndOfCandidates(e){return void 0===e?\"\":\"a=end-of-candidates\"+this.eol}printRTPRelated(e){if(!e.payloads)return\"\";const t=e.payloads;let i=\"\";i+=e.rtcpFeedbackWildcards.map((e=>this.printRTCPFeedback(\"*\",e))).join(\"\");for(const e of t)i+=this.printRtpMap(e.payloadType,e.rtpMap),i+=this.printFmtp(e.payloadType,e.fmtp),i+=e.rtcpFeedbacks.map((t=>this.printRTCPFeedback(e.payloadType,t))).join(\"\");return i}printFmtp(e,t){if(!t)return\"\";const i=Object.keys(t.parameters);return 1===i.length&&null===t.parameters[i[0]]?\"a=fmtp:\".concat(e).concat(s).concat(i[0]).concat(this.eol):\"a=fmtp:\".concat(e).concat(s).concat(Object.keys(t.parameters).map((e=>\"\".concat(e,\"=\").concat(t.parameters[e]))).join(\";\")).concat(this.eol)}printRtpMap(e,t){return t?\"a=rtpmap:\".concat(e).concat(s).concat(t.encodingName,\"/\").concat(t.clockRate).concat(t.encodingParameters?\"/\".concat(t.encodingParameters):\"\").concat(this.eol):\"\"}printRTCPFeedback(e,t){let i=\"a=rtcp-fb:\".concat(e).concat(s),n=t;return\"trr-int\"===n.type?i+=\"ttr-int\".concat(s).concat(n.interval):(i+=\"\".concat(n.type),n.parameter&&(i+=\"\".concat(s).concat(n.parameter),n.additional&&(i+=\"\".concat(s).concat(n.additional)))),i+this.eol}printPtime(e){return void 0===e?\"\":\"a=ptime:\".concat(e).concat(this.eol)}printMaxPtime(e){return void 0===e?\"\":\"a=maxptime:\".concat(e).concat(this.eol)}printDirection(e){return void 0===e?\"\":\"a=\".concat(e).concat(this.eol)}printSSRC(e){return e.map((e=>Object.keys(e.attributes).map((t=>\"a=ssrc:\".concat(e.ssrcId.toString(10)).concat(s).concat(t).concat(e.attributes[t]?\":\".concat(e.attributes[t]):\"\").concat(this.eol))).join(\"\"))).join(\"\")}printRTCPMux(e){return void 0===e?\"\":\"a=rtcp-mux\".concat(this.eol)}printRTCPMuxOnly(e){return void 0===e?\"\":\"a=rtcp-mux-only\".concat(this.eol)}printRTCPRsize(e){return void 0===e?\"\":\"a=rtcp-rsize\".concat(this.eol)}printRTCP(e){if(void 0===e)return\"\";let t=\"a=rtcp:\".concat(e.port);return e.netType&&(t+=\"\".concat(s).concat(e.netType)),e.addressType&&(t+=\"\".concat(s).concat(e.addressType)),e.address&&(t+=\"\".concat(s).concat(e.address)),t+this.eol}printMSId(e){return e.map((e=>\"a=msid:\".concat(e.id).concat(e.appdata?\"\".concat(s).concat(e.appdata):\"\").concat(this.eol))).join(\"\")}printImageattr(e){return e.map((e=>\"a=imageattr:\".concat(e).concat(this.eol))).join(\"\")}printRid(e){return e.map((e=>{let t=\"a=rid:\".concat(e.id).concat(s).concat(e.direction);return e.payloads&&(t+=\"\".concat(s,\"pt=\").concat(e.payloads.join(\",\"))),e.params.length>0&&(t+=\"\".concat(s).concat(e.params.map((e=>\"depend\"===e.type?\"depend=\".concat(e.rids.join(\",\")):\"\".concat(e.type,\"=\").concat(e.val))).join(\";\"))),t+this.eol})).join(\"\")}printSimulcast(e){return void 0===e?\"\":\"a=simulcast:\".concat(e).concat(this.eol)}printSCTPPort(e){return void 0===e?\"\":\"a=sctp-port:\".concat(e).concat(this.eol)}printMaxMessageSize(e){return void 0===e?\"\":\"a=max-message-size:\".concat(e).concat(this.eol)}printMid(e){return void 0===e?\"\":\"a=mid:\".concat(e).concat(this.eol)}printSSRCGroups(e){return e.map((e=>\"a=ssrc-group:\".concat(e.semantic).concat(e.ssrcIds.map((e=>\"\".concat(s).concat(e.toString(10)))).join(\"\")).concat(this.eol))).join(\"\")}}function D(e){return(new C).parse(e)}function P(e,t){return(new b).print(e,t)}}},t={};function i(n){if(t[n])return t[n].exports;var r=t[n]={exports:{}};return e[n](r,r.exports,i),r.exports}return i.d=(e,t)=>{for(var n in t)i.o(t,n)&&!i.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),i.r=e=>{\"undefined\"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:\"Module\"}),Object.defineProperty(e,\"__esModule\",{value:!0})},i(8)})()}(zU);var JU=zU.exports;function XU(e){if(Array.isArray(e))return e.map((e=>e));if(!QU(e))return e;const t={};for(const i in e){const n=e[i];QU(n)||Array.isArray(n)?t[i]=XU(n):t[i]=n}return t}function QU(e){return!(\"object\"!=typeof e||Array.isArray(e)||!e)}class ZU{constructor(e){sh(this,\"input\",[]),sh(this,\"size\",void 0),this.size=e}add(e){this.input.push(e),this.input.length>this.size&&this.input.splice(0,1)}diffMean(){return 0===this.input.length?0:(this.input[this.input.length-1]-this.input[0])/this.input.length}}const $U={address:\"unknown\",candidateType:\"unknown\",id:\"unknown\",port:0,priority:0,protocol:\"unknown\",type:\"unknown\"},ex={timestamp:0,bitrate:{actualEncoded:0,transmit:0},sendPacketLossRate:0,recvPacketLossRate:0,videoRecv:[],videoSend:[],audioRecv:[],audioSend:[],selectedCandidatePair:{id:\"unknown\",localCandidate:$U,remoteCandidate:$U}},tx={firsCount:0,nacksCount:0,plisCount:0,framesDecodeCount:0,framesDecodeInterval:0,framesDecodeFreezeTime:0,decodeFrameRate:0,bytes:0,packetsLost:0,packetLostRate:0,packets:0,ssrc:0,qpSumPerFrame:0},ix={firsCount:0,nacksCount:0,plisCount:0,frameCount:0,bytes:0,packets:0,packetsLost:0,packetLostRate:0,ssrc:0,rttMs:0,jitterMs:0,qpSumPerFrame:0},nx={bytes:0,packets:0,packetsLost:0,packetLostRate:0,ssrc:0,rttMs:0,jitterMs:0},rx={jitterBufferMs:0,jitterMs:0,bytes:0,packetsLost:0,packetLostRate:0,packets:0,ssrc:0,receivedFrames:0,droppedFrames:0,concealedSamples:0};function sx(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function ox(e){for(var t=1;t{this.updateStats()}),this.options.updateInterval)}getStats(){return this.stats}getSelectedCandidatePair(){return new cg((e=>{e({local:ox({},$U),remote:ox({},$U)})}))}setVideoIsReady(e){this.videoIsReady=e}setVideoIsReady2(e,t){this.videoIsReady2[e]=t}getVideoIsReady(e){return this.videoIsReady2[e]||!1}setIsFirstAudioDecoded(e){}destroy(){window.clearInterval(this.intervalTimer),this.pc=void 0}calcLossRate(e){this.lossRateWindowStats.push(e),this.lossRateWindowStats.length>this.options.lossRateInterval&&this.lossRateWindowStats.splice(0,1);const t=this.lossRateWindowStats.length,i=[\"videoSend\",\"audioSend\",\"videoRecv\",\"audioRecv\"];let n=0,r=0,s=0,o=0;for(const a of i)e[a].forEach(((e,i)=>{if(!this.lossRateWindowStats[t-1][a][i]||!this.lossRateWindowStats[0][a][i])return;const c=this.lossRateWindowStats[t-1][a][i].packets-this.lossRateWindowStats[0][a][i].packets,d=this.lossRateWindowStats[t-1][a][i].packetsLost-this.lossRateWindowStats[0][a][i].packetsLost;\"videoSend\"===a||\"audioSend\"===a?(n+=c,s+=d):(r+=c,o+=d),Number.isNaN(c)||Number.isNaN(c)?e.packetLostRate=0:e.packetLostRate=c<=0||d<=0?0:d/(c+d)}));e.sendPacketLossRate=n<=0||s<=0?0:s/(n+s),e.recvPacketLossRate=r<=0||o<=0?0:o/(r+o)}}function cx(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function dx(e){for(var t=1;t\"ssrc\"===e.type));this.processSSRCStats(i);const n=t.find((e=>\"VideoBwe\"===e.type));n&&this.processBandwidthStats(n),this._stats.timestamp=Date.now(),this.calcLossRate(this._stats),this.stats=this._stats}processBandwidthStats(e){this._stats.bitrate={actualEncoded:Number(e.googActualEncBitrate),targetEncoded:Number(e.googTargetEncBitrate),retransmit:Number(e.googRetransmitBitrate),transmit:Number(e.googTransmitBitrate)},this._stats.sendBandwidth=Number(e.googAvailableSendBandwidth)}processSSRCStats(e){e.forEach((e=>{var t;const i=bn(t=e.id).call(t,\"send\");switch(\"\".concat(e.mediaType,\"_\").concat(i?\"send\":\"recv\")){case\"video_send\":{const t=XU(ix);t.codec=e.googCodecName,t.adaptionChangeReason=\"none\",e.googCpuLimitedResolution&&(t.adaptionChangeReason=\"cpu\"),e.googBandwidthLimitedResolution&&(t.adaptionChangeReason=\"bandwidth\"),t.avgEncodeMs=Number(e.googAvgEncodeMs),t.inputFrame={width:Number(e.googFrameWidthInput)||Number(e.googFrameWidthSent),height:Number(e.googFrameHeightInput)||Number(e.googFrameHeightSent),frameRate:Number(e.googFrameRateInput)},t.sentFrame={width:Number(e.googFrameWidthSent),height:Number(e.googFrameHeightSent),frameRate:Number(e.googFrameRateInput)},t.firsCount=Number(e.googFirReceived),t.nacksCount=Number(e.googNacksReceived),t.plisCount=Number(e.googPlisReceived),t.frameCount=Number(e.framesEncoded),t.bytes=Number(e.bytesSent),t.packets=Number(e.packetsSent),t.packetsLost=Number(e.packetsLost),t.ssrc=Number(e.ssrc),t.rttMs=Number(e.googRtt||0),this._stats.videoSend.push(t),this._stats.rtt=t.rttMs;break}case\"video_recv\":{const t=XU(tx),i=this.lastDecodeVideoReceiverStats.get(Number(e.ssrc));if(t.codec=e.googCodecName,t.targetDelayMs=Number(e.googTargetDelayMs),t.renderDelayMs=Number(e.googRenderDelayMs),t.currentDelayMs=Number(e.googCurrentDelayMs),t.minPlayoutDelayMs=Number(e.googMinPlayoutDelayMs),t.decodeMs=Number(e.googDecodeMs),t.maxDecodeMs=Number(e.googMaxDecodeMs),t.receivedFrame={width:Number(e.googFrameWidthReceived),height:Number(e.googFrameHeightReceived),frameRate:Number(e.googFrameRateReceived)},t.decodedFrame={width:Number(e.googFrameWidthReceived),height:Number(e.googFrameHeightReceived),frameRate:Number(e.googFrameRateDecoded)},t.decodeFrameRate=Number(e.googFrameRateDecoded),t.outputFrame={width:Number(e.googFrameWidthReceived),height:Number(e.googFrameHeightReceived),frameRate:Number(e.googFrameRateOutput)},t.jitterBufferMs=Number(e.googJitterBufferMs),t.firsCount=Number(e.googFirsSent),t.nacksCount=Number(e.googNacksSent),t.plisCount=Number(e.googPlisSent),t.framesDecodeCount=Number(e.framesDecoded),t.bytes=Number(e.bytesReceived),t.packets=Number(e.packetsReceived),t.packetsLost=Number(e.packetsLost),t.ssrc=Number(e.ssrc),t.packets>0&&!this.isFirstVideoReceived[t.ssrc]&&(this.onFirstVideoReceived&&this.onFirstVideoReceived(t.ssrc),this.isFirstVideoReceived[t.ssrc]=!0),t.framesDecodeCount>0&&!this.isFirstVideoDecoded[t.ssrc]&&(this.onFirstVideoDecoded&&this.onFirstVideoDecoded(t.ssrc,t.decodedFrame.width,t.decodedFrame.height),this.isFirstVideoDecoded[t.ssrc]=!0),i){const n=i.stats,r=Date.now()-i.lts;t.framesDecodeFreezeTime=n.framesDecodeFreezeTime,t.framesDecodeInterval=n.framesDecodeInterval,t.framesDecodeCount>n.framesDecodeCount&&this.isFirstVideoDecoded[t.ssrc]?(i.lts=Date.now(),t.framesDecodeInterval=r,t.framesDecodeInterval>=this.options.freezeRateLimit&&(this.getVideoIsReady(parseInt(e.ssrc,10))?t.framesDecodeFreezeTime+=t.framesDecodeInterval:this.setVideoIsReady2(parseInt(e.ssrc,10),!0))):t.framesDecodeCount0&&!this.isFirstAudioReceived[t.ssrc]&&(this.onFirstAudioReceived&&this.onFirstAudioReceived(t.ssrc),this.isFirstAudioReceived[t.ssrc]=!0),t.decodingNormal>0&&!this.isFirstAudioDecoded[t.ssrc]&&(this.onFirstAudioDecoded&&this.onFirstAudioDecoded(t.ssrc),this.isFirstAudioDecoded[t.ssrc]=!0),this._stats.audioRecv.push(t);break}case\"audio_send\":{const t=XU(nx);t.codec=e.googCodecName,t.inputLevel=Math.abs(Number(e.audioInputLevel))/32767,t.aecReturnLoss=Number(e.googEchoCancellationReturnLoss||0),t.aecReturnLossEnhancement=Number(e.googEchoCancellationReturnLossEnhancement||0),t.residualEchoLikelihood=Number(e.googResidualEchoLikelihood||0),t.residualEchoLikelihoodRecentMax=Number(e.googResidualEchoLikelihoodRecentMax||0),t.bytes=Number(e.bytesSent),t.packets=Number(e.packetsSent),t.packetsLost=Number(e.packetsLost),t.ssrc=Number(e.ssrc),t.rttMs=Number(e.googRtt||0),this._stats.rtt=t.rttMs,this._stats.audioSend.push(t);break}}}))}_getStats(){return new cg(((e,t)=>{this.pc.getStats(e,t)}))}statsResponsesToObjects(e){const t=[];return e.result().forEach((e=>{const i={id:e.id,timestamp:e.timestamp.valueOf().toString(),type:e.type};e.names().forEach((t=>{i[t]=e.stat(t)})),t.push(i)})),t}}function ux(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function hx(e){for(var t=1;t{switch(e.type){case aI.OUTBOUND:case aI.INBOUND:{const t=e.mediaType||e.kind,i=!t&&\"frameWidth\"in e,n=!t&&!(\"frameWidth\"in e);e.type===aI.OUTBOUND?\"audio\"===t||n?this.processAudioOutboundStats(e):(\"video\"===t||i)&&this.processVideoOutboundStats(e):e.type===aI.INBOUND&&(\"audio\"===t||n?this.processAudioInboundStats(e):(\"video\"===t||i)&&this.processVideoInboundStats(e));break}case aI.TRANSPORT:{const t=this.report.get(e.selectedCandidatePairId);t&&this.processCandidatePairStats(t);break}case aI.CANDIDATE_PAIR:e.selected&&this.processCandidatePairStats(e)}})),this.updateSendBitrate(),this._stats.timestamp=Date.now(),this.calcLossRate(this._stats),this.stats=this._stats}async getSelectedCandidatePair(){const e=await this.pc.getStats(),t={local:hx({},$U),remote:hx({},$U)};return e.forEach((i=>{let n;if(i.type===aI.TRANSPORT&&(n=e.get(i.selectedCandidatePairId)),i.type===aI.CANDIDATE_PAIR&&i.selected&&(n=i),n){const i=(e,t)=>{e.type=t.type,e.id=t.id,t.address&&(e.address=t.address),t.candidateType&&(e.candidateType=t.candidateType),t.port&&(e.port=t.port),t.priority&&(e.priority=t.priority),t.protocol&&(e.protocol=t.protocol),t.relayProtocol&&(e.relayProtocol=t.relayProtocol)};if(n.localCandidateId){const r=e.get(n.localCandidateId);r&&i(t.local,r)}if(n.remoteCandidateId){const r=e.get(n.remoteCandidateId);r&&i(t.remote,r)}}})),t}processCandidatePairStats(e){if(this._stats.sendBandwidth=e.availableOutgoingBitrate||0,e.currentRoundTripTime&&(this._stats.rtt=1e3*e.currentRoundTripTime),this._stats.videoSend.forEach((t=>{e.currentRoundTripTime&&(t.rttMs=1e3*e.currentRoundTripTime)})),this._stats.audioSend.forEach((t=>{e.currentRoundTripTime&&(t.rttMs=1e3*e.currentRoundTripTime)})),this._stats.selectedCandidatePair.id=e.id,e.localCandidateId){const t=this.report.get(e.localCandidateId);t&&this.processCandidateStats(t)}if(e.remoteCandidateId){const t=this.report.get(e.remoteCandidateId);t&&this.processCandidateStats(t)}}processCandidateStats(e){let t;e.type===aI.LOCAL_CANDIDATE&&(t=this._stats.selectedCandidatePair.localCandidate),e.type===aI.REMOTE_CANDIDATE&&(t=this._stats.selectedCandidatePair.remoteCandidate),t&&(t.type=e.type,t.id=e.id,e.address&&(t.address=e.address),e.candidateType&&(t.candidateType=e.candidateType),e.port&&(t.port=e.port),e.priority&&(t.priority=e.priority),e.protocol&&(t.protocol=e.protocol),e.relayProtocol&&(t.relayProtocol=e.relayProtocol),e.type===aI.LOCAL_CANDIDATE&&this.stats.selectedCandidatePair.localCandidate.id!==t.id&&this.onSelectedLocalCandidateChanged&&this.onSelectedLocalCandidateChanged(hx({},t),hx({},this.stats.selectedCandidatePair.localCandidate)),e.type===aI.REMOTE_CANDIDATE&&this.stats.selectedCandidatePair.remoteCandidate.id!==t.id&&this.onSelectedRemoteCandidateChanged&&this.onSelectedRemoteCandidateChanged(hx({},t),hx({},this.stats.selectedCandidatePair.remoteCandidate)))}processAudioInboundStats(e){let t=this._stats.audioRecv.find((t=>t.ssrc===e.ssrc));t||(t=XU(rx),this._stats.audioRecv.push(t)),t.ssrc=e.ssrc,t.packets=e.packetsReceived,t.packetsLost=e.packetsLost,t.bytes=e.bytesReceived,t.jitterMs=1e3*e.jitter,this.processAudioTrackReceiverStats(e,e.trackId,t),e.codecId&&(t.codec=this.getCodecFromCodecStats(e.codecId)),t.receivedFrames||(t.receivedFrames=e.packetsReceived),t.droppedFrames||(t.droppedFrames=e.packetsLost),t.receivedFrames>0&&!this.isFirstAudioReceived[t.ssrc]&&(this.onFirstAudioReceived&&this.onFirstAudioReceived(t.ssrc),this.isFirstAudioReceived[t.ssrc]=!0),t.outputLevel&&t.outputLevel>0&&!this.isFirstAudioDecoded[t.ssrc]&&(this.onFirstAudioDecoded&&this.onFirstAudioDecoded(t.ssrc),this.isFirstAudioDecoded[t.ssrc]=!0),\"number\"==typeof e.concealedSamples&&(t.concealedSamples=e.concealedSamples)}processVideoInboundStats(e){let t=this._stats.videoRecv.find((t=>t.ssrc===e.ssrc));t||(t=XU(tx),this._stats.videoRecv.push(t)),t.ssrc=e.ssrc,t.packets=e.packetsReceived,t.packetsLost=e.packetsLost,t.bytes=e.bytesReceived,t.firsCount=e.firCount,t.nacksCount=e.nackCount,t.plisCount=e.pliCount,t.framesDecodeCount=e.framesDecoded,t.totalInterFrameDelay=e.totalInterFrameDelay,t.totalSquaredInterFrameDelay=e.totalSquaredInterFrameDelay;const i=this.lastDecodeVideoReceiverStats.get(t.ssrc),n=this.lastVideoFramesDecode.get(t.ssrc),r=Date.now();if(t.framesDecodeCount>0&&!this.isFirstVideoDecoded[t.ssrc]){const e=t.decodedFrame?t.decodedFrame.width:0,i=t.decodedFrame?t.decodedFrame.height:0;this.onFirstVideoDecoded&&this.onFirstVideoDecoded(t.ssrc,e,i),this.isFirstVideoDecoded[t.ssrc]=!0}if(i){const n=i.stats,s=r-i.lts;t.framesDecodeFreezeTime=n.framesDecodeFreezeTime,t.framesDecodeInterval=n.framesDecodeInterval,!this.isFirstVideoDecoded[t.ssrc]&&s>this.options.firstVideoDecodedTimeout&&!this.isFirstVideoDecodedTimeout[t.ssrc]&&(this.onFirstVideoDecodedTimeout&&this.onFirstVideoDecodedTimeout(t.ssrc),this.isFirstVideoDecodedTimeout[t.ssrc]=!0),t.framesDecodeCount>n.framesDecodeCount&&this.isFirstVideoDecoded[t.ssrc]?(i.lts=Date.now(),t.framesDecodeInterval=s,t.framesDecodeInterval>=this.options.freezeRateLimit&&(this.getVideoIsReady(parseInt(e.ssrc))?t.framesDecodeFreezeTime+=t.framesDecodeInterval:this.setVideoIsReady2(parseInt(e.ssrc,10),!0))):t.framesDecodeCounte.framesDecoded?t.qpSumPerFrame=e.qpSum/e.framesDecoded:t.qpSumPerFrame=(e.qpSum-i.qpSum)/(e.framesDecoded-i.stats.framesDecodeCount))}n&&r-n.lts>=800?(t.decodeFrameRate=Math.round((t.framesDecodeCount-n.count)/((r-n.lts)/1e3)),this.lastVideoFramesDecode.set(t.ssrc,{count:t.framesDecodeCount,lts:r,rate:t.decodeFrameRate})):n?t.decodeFrameRate=n.rate:this.lastVideoFramesDecode.set(t.ssrc,{count:t.framesDecodeCount,lts:r,rate:0}),e.totalDecodeTime&&(t.decodeMs=1e3*e.totalDecodeTime),this.processVideoTrackReceiverStats(e,e.trackId,t),e.codecId&&(t.codec=this.getCodecFromCodecStats(e.codecId)),e.framerateMean&&(t.framesRateFirefox=e.framerateMean),t.packets>0&&!this.isFirstVideoReceived[t.ssrc]&&(this.onFirstVideoReceived&&this.onFirstVideoReceived(t.ssrc),this.isFirstVideoReceived[t.ssrc]=!0),this.lastDecodeVideoReceiverStats.set(t.ssrc,{stats:hx({},t),lts:i?i.lts:Date.now(),qpSum:e.qpSum})}processVideoOutboundStats(e){let t=this._stats.videoSend.find((t=>t.ssrc===e.ssrc));t||(t=XU(ix),this._stats.videoSend.push(t));const i=this.mediaBytesSent.get(e.ssrc);if(i)i.add(e.bytesSent);else{const t=new ZU(10);t.add(e.bytesSent),this.mediaBytesSent.set(e.ssrc,t)}if(void 0!==e.retransmittedBytesSent){const t=this.mediaBytesRetransmit.get(e.ssrc);if(t)t.add(e.retransmittedBytesSent);else{const t=new ZU(10);t.add(e.retransmittedBytesSent),this.mediaBytesRetransmit.set(e.ssrc,t)}}if(e.totalEncodedBytesTarget){const t=this.mediaBytesTargetEncode.get(e.ssrc);if(t)t.add(e.totalEncodedBytesTarget);else{const t=new ZU(10);t.add(e.totalEncodedBytesTarget),this.mediaBytesTargetEncode.set(e.ssrc,t)}}if(t.ssrc=e.ssrc,t.bytes=e.bytesSent,t.packets=e.packetsSent,t.firsCount=e.firCount,t.nacksCount=e.nackCount,t.plisCount=e.pliCount,t.frameCount=e.framesEncoded,t.adaptionChangeReason=e.qualityLimitationReason,t.scalabilityMode=e.scalabilityMode,e.totalEncodeTime&&e.framesEncoded){const i=this.lastEncoderMs.get(e.ssrc);if(!i||i.lastFrameCount>e.framesEncoded)t.avgEncodeMs=1e3*e.totalEncodeTime/e.framesEncoded;else{const n=e.framesEncoded-i.lastFrameCount,r=e.totalEncodeTime-i.lastEncoderTime;t.avgEncodeMs=1e3*r/n}}if(e.framesEncoded&&e.qpSum){const i=this.lastEncoderMs.get(e.ssrc);!i||i.lastFrameCount>e.framesEncoded?t.qpSumPerFrame=e.qpSum/e.framesEncoded:t.qpSumPerFrame=(e.qpSum-i.lastQpSum)/(e.framesEncoded-i.lastFrameCount)}if(this.lastEncoderMs.set(e.ssrc,{lastFrameCount:e.framesEncoded,lastEncoderTime:e.totalEncodeTime,lastQpSum:e.qpSum,lts:Date.now()}),e.codecId&&(t.codec=this.getCodecFromCodecStats(e.codecId)),e.mediaSourceId&&this.processVideoMediaSource(e.mediaSourceId,t),this.processVideoTrackSenderStats(e,e.trackId,t),e.remoteId)this.processRemoteInboundStats(e.remoteId,t);else{const i=this.findRemoteStatsId(e.ssrc,aI.REMOTE_INBOUND);i&&this.processRemoteInboundStats(i,t)}}processAudioOutboundStats(e){let t=this._stats.audioSend.find((t=>t.ssrc===e.ssrc));if(t||(t=XU(nx),this._stats.audioSend.push(t)),t.ssrc=e.ssrc,t.packets=e.packetsSent,t.bytes=e.bytesSent,e.mediaSourceId&&this.processAudioMediaSource(e.mediaSourceId,t),e.codecId&&(t.codec=this.getCodecFromCodecStats(e.codecId)),this.processAudioTrackSenderStats(e,e.trackId,t),e.remoteId)this.processRemoteInboundStats(e.remoteId,t);else{const i=this.findRemoteStatsId(e.ssrc,aI.REMOTE_INBOUND);i&&this.processRemoteInboundStats(i,t)}}findRemoteStatsId(e,t){var i;const n=Array.from(NI(i=this.report).call(i)).find((i=>i.type===t&&i.ssrc===e));return n?n.id:null}processVideoMediaSource(e,t){const i=this.report.get(e);i&&i.width&&i.height&&i.framesPerSecond&&(t.inputFrame={width:i.width,height:i.height,frameRate:i.framesPerSecond})}processAudioMediaSource(e,t){const i=this.report.get(e);i&&(t.inputLevel=i.audioLevel)}processVideoTrackSenderStats(e,t,i){var n,r,s,o;const a=t?this.report.get(t):void 0,c=null!==(n=null==a?void 0:a.framesSent)&&void 0!==n?n:e.framesSent;if(\"number\"!=typeof c)return;let d=null!==(r=null==a?void 0:a.frameWidth)&&void 0!==r?r:e.frameWidth,l=null!==(s=null==a?void 0:a.frameHeight)&&void 0!==s?s:e.frameHeight,u=null!==(o=null==a?void 0:a.framesPerSecond)&&void 0!==o?o:e.framesPerSecond;if(\"number\"==typeof d&&\"number\"==typeof l||(d=0,l=0),null==u){const e=Date.now(),t=this.lastVideoFramesSent.get(i.ssrc);t&&e-t.lts>=800?(u=Math.round((c-t.count)/((e-t.lts)/1e3)),this.lastVideoFramesSent.set(i.ssrc,{count:c,lts:e,rate:u})):t?u=t.rate:this.lastVideoFramesSent.set(i.ssrc,{count:c,lts:e,rate:0})}i.sentFrame={width:d,height:l,frameRate:Math.max(0,u)}}processVideoTrackReceiverStats(e,t,i){var n,r,s,o,a;const c=t?this.report.get(t):void 0,d=null!==(n=null==c?void 0:c.framesReceived)&&void 0!==n?n:e.framesReceived,l=null!==(r=null==c?void 0:c.frameWidth)&&void 0!==r?r:e.frameWidth,u=null!==(s=null==c?void 0:c.frameHeight)&&void 0!==s?s:e.frameHeight,h=null!==(o=null==c?void 0:c.jitterBufferDelay)&&void 0!==o?o:e.jitterBufferDelay,p=null!==(a=null==c?void 0:c.jitterBufferEmittedCount)&&void 0!==a?a:e.jitterBufferEmittedCount;if(\"number\"==typeof d){const e=this.lastVideoFramesRecv.get(i.ssrc),t=Date.now();i.framesReceivedCount=d;let n=0;e&&t-e.lts>=800?(n=Math.round((d-e.count)/((t-e.lts)/1e3)),this.lastVideoFramesRecv.set(i.ssrc,{count:d,lts:t,rate:n})):e?n=e.rate:this.lastVideoFramesRecv.set(i.ssrc,{count:d,lts:t,rate:0}),i.receivedFrame={width:l||0,height:u||0,frameRate:n||0},i.decodedFrame={width:l||0,height:u||0,frameRate:i.decodeFrameRate||0},i.outputFrame={width:l||0,height:u||0,frameRate:i.decodeFrameRate||0}}if(h&&p){const e=this.lastVideoJBDelay.get(i.ssrc)||{jitterBufferDelay:0,jitterBufferEmittedCount:0,jitterBufferMs:0};let t=e.jitterBufferMs;const n=p-e.jitterBufferEmittedCount;n>0&&(t=1e3*(h-e.jitterBufferDelay)/n),i.jitterBufferMs=t,i.currentDelayMs=Math.round(t),this.lastVideoJBDelay.set(i.ssrc,{jitterBufferDelay:h,jitterBufferEmittedCount:p,jitterBufferMs:i.currentDelayMs})}}processAudioTrackSenderStats(e,t,i){var n,r,s,o;const a=t?this.report.get(t):void 0,c=null!==(n=null!==(r=null==a?void 0:a.echoReturnLoss)&&void 0!==r?r:e.echoReturnLoss)&&void 0!==n?n:0,d=null!==(s=null!==(o=null==a?void 0:a.echoReturnLossEnhancement)&&void 0!==o?o:e.echoReturnLossEnhancement)&&void 0!==s?s:0;i.aecReturnLoss=c,i.aecReturnLossEnhancement=d}processAudioTrackReceiverStats(e,t,i){var n,r,s,o,a,c,d;const l=t?this.report.get(t):void 0,u=null!==(n=null==l?void 0:l.removedSamplesForAcceleration)&&void 0!==n?n:e.removedSamplesForAcceleration,h=null!==(r=null==l?void 0:l.totalSamplesReceived)&&void 0!==r?r:e.totalSamplesReceived,p=null!==(s=null==l?void 0:l.jitterBufferDelay)&&void 0!==s?s:e.jitterBufferDelay,_=null!==(o=null==l?void 0:l.jitterBufferEmittedCount)&&void 0!==o?o:e.jitterBufferEmittedCount,E=null!==(a=null==l?void 0:l.audioLevel)&&void 0!==a?a:null==e?void 0:e.audioLevel,m=null!==(c=null==l?void 0:l.totalSamplesDuration)&&void 0!==c?c:null==e?void 0:e.totalSamplesDuration,f=null!==(d=null==l?void 0:l.concealedSamples)&&void 0!==d?d:e.concealedSamples;if(u&&h&&(i.accelerateRate=u/h),p&&_){const e=this.lastAudioJBDelay.get(i.ssrc)||{jitterBufferDelay:0,jitterBufferEmittedCount:0,jitterBufferMs:0};let t=e.jitterBufferMs;const n=_-e.jitterBufferEmittedCount;n>0&&(t=1e3*(p-e.jitterBufferDelay)/n),i.jitterBufferMs=Math.round(t),this.lastAudioJBDelay.set(i.ssrc,{jitterBufferDelay:p,jitterBufferEmittedCount:_,jitterBufferMs:i.jitterBufferMs})}i.outputLevel=E;let g=1920;m&&h&&(g=h/m/50,i.receivedFrames=Math.round(h/g)),f&&(i.droppedFrames=Math.round(f/g))}processRemoteInboundStats(e,t){const i=this.report.get(e);i&&(t.packetsLost=i.packetsLost,i.roundTripTime&&(t.rttMs=1e3*i.roundTripTime),i.jitter&&(t.jitterMs=1e3*i.jitter),i.timestamp&&(t.timestamp=i.timestamp))}getCodecFromCodecStats(e){const t=this.report.get(e);if(!t)return\"\";const i=t.mimeType.match(/\\/(.*)$/);return i&&i[1]?i[1]:\"\"}updateSendBitrate(){let e=0,t=null,i=null;this.mediaBytesSent.forEach((t=>{e+=t.diffMean()})),this.mediaBytesRetransmit.forEach((e=>{t=null===t?e.diffMean():t+e.diffMean()})),this.mediaBytesTargetEncode.forEach((e=>{i=null===i?e.diffMean():i+e.diffMean()}));const n=null!==t?e-t:e;this._stats.bitrate={actualEncoded:8*n/(this.options.updateInterval/1e3),transmit:8*e/(this.options.updateInterval/1e3)},null!==t&&(this._stats.bitrate.retransmit=8*t/(this.options.updateInterval/1e3)),null!==i&&(this._stats.bitrate.targetEncoded=8*i/(this.options.updateInterval/1e3))}}class _x extends ax{updateStats(){return cg.resolve()}}function Ex(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:250,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:8,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:500,r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:1e4;const s=function(){const e=navigator.userAgent.toLocaleLowerCase().match(/chrome\\/[\\d]*/i);return e&&e[0]?Number(e[0].split(\"/\")[1]):null}();return s?s<76?new lx(e,{updateInterval:t,lossRateInterval:i,freezeRateLimit:n,firstVideoDecodedTimeout:r}):new px(e,{updateInterval:t,lossRateInterval:i,freezeRateLimit:n,firstVideoDecodedTimeout:r}):function(e){return!!window.RTCStatsReport&&e.getStats()instanceof cg}(e)?new px(e,{updateInterval:t,lossRateInterval:i,freezeRateLimit:n,firstVideoDecodedTimeout:r}):new _x(e,{updateInterval:t,lossRateInterval:i,freezeRateLimit:n,firstVideoDecodedTimeout:r})}function mx(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function fx(e){for(var t=1;t1&&void 0!==arguments[1]?arguments[1]:{},i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=arguments.length>3?arguments[3]:void 0;const{filterRTX:r,filterVideoFec:s,filterAudioFec:o,filterAudioCodec:a,filterVideoCodec:c}=t,{useXR:d}=i;let l=[],u=[],h=[],p=[],_=!1,E=!1;if(JU.parse(e).mediaDescriptions.forEach((e=>{n&&n!==e.attributes.direction||(\"video\"!==e.media.mediaType||_||(u=e.attributes.payloads,p=e.attributes.extmaps,_=!0),\"audio\"!==e.media.mediaType||E||(l=e.attributes.payloads,h=e.attributes.extmaps,E=!0))})),!p||0===u.length)throw new Error(\"Cannot get video capabilities from SDP.\");if(!h||0===l.length)throw new Error(\"Cannot get audio capabilities from SDP.\");u.forEach((e=>{var t;null!==(t=e.rtpMap)&&void 0!==t&&t.clockRate&&(e.rtpMap.clockRate=parseInt(e.rtpMap.clockRate)),d&&e.rtcpFeedbacks.push({type:\"rrtr\"})})),l.forEach((e=>{var t;null!==(t=e.rtpMap)&&void 0!==t&&t.clockRate&&(e.rtpMap.clockRate=parseInt(e.rtpMap.clockRate)),d&&e.rtcpFeedbacks.push({type:\"rrtr\"})})),r&&(l=l.filter((e=>{var t;return\"rtx\"!==(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())})),u=u.filter((e=>{var t;return\"rtx\"!==(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())}))),s&&(u=u.filter((e=>{var t;return!/(red)|(ulpfec)|(flexfec)/i.test((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName)||\"\")}))),o&&(l=l.filter((e=>{var t;return!/(red)|(ulpfec)|(flexfec)/i.test((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName)||\"\")}))),a&&(null==a?void 0:a.length)>0&&(l=l.filter((e=>{var t;return bn(a).call(a,(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())||\"\")}))),c&&(null==c?void 0:c.length)>0&&(u=u.filter((e=>{var t;return bn(c).call(c,(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())||\"\")})));const m=RC(\"UNSUPPORTED_VIDEO_CODEC\");return m&&m.length>0&&(u=u.filter((e=>!(e.rtpMap&&bn(m).call(m,e.rtpMap.encodingName.toLowerCase()))))),{audioCodecs:l,videoCodecs:u,audioExtensions:h,videoExtensions:p}}function Tx(e){const t=JU.parse(e);let i,n;for(const e of t.mediaDescriptions){if(!i){const t=e.attributes.iceUfrag,n=e.attributes.icePwd;if(!t||!n)throw new Error(\"Cannot get iceUfrag or icePwd from SDP.\");i={iceUfrag:t,icePwd:n}}if(!n){const t=e.attributes.fingerprints;t.length>0&&(n={fingerprints:t})}}if(!n&&t.attributes.fingerprints.length>0&&(n={fingerprints:t.attributes.fingerprints}),!n||!i)throw new Error(\"Cannot get iceParameters or dtlsParameters from SDP.\");return{iceParameters:i,dtlsParameters:n}}function Sx(e,t){const i=[],n=e.attributes.ssrcGroups.filter((e=>\"FID\"===e.semantic)),r=e.attributes.ssrcGroups.find((e=>\"SIM\"===e.semantic)),s=e.attributes.ssrcs;if(r)r.ssrcIds.forEach((e=>{var r;const s=null===(r=n.find((t=>t.ssrcIds[0]===e)))||void 0===r?void 0:r.ssrcIds[1];i.push({ssrcId:e,rtx:t?s:void 0})}));else if(n.length>0){const e=n[0].ssrcIds[0],r=n[0].ssrcIds[1];i.push({ssrcId:e,rtx:t?r:void 0})}else{if(0===s.length)throw new Error(\"No ssrcs found on local media description.\");i.push({ssrcId:s[0].ssrcId})}return i}function Rx(e,t){const{cname:i}=e;let n;t&&t.ip&&\"number\"==typeof t.port?(n=[{foundation:\"udpcandidate\",componentId:\"1\",transport:\"udp\",priority:\"2103266323\",connectionAddress:t.ip,port:t.port.toString(),type:\"host\",extension:{}}],jC.debug(\"Using remote candidate from AP \".concat(t.ip,\":\").concat(t.port)),t.ip6&&(n.push({foundation:\"udpcandidate\",componentId:\"1\",transport:\"udp\",priority:\"2103266323\",connectionAddress:t.ip6,port:t.port.toString(),type:\"host\",extension:{}}),jC.debug(\"Using IPV6 remote candidate from AP \".concat(t.ip6,\":\").concat(t.port)))):n=e.iceParameters.candidates.map((e=>({foundation:e.foundation,componentId:\"1\",transport:e.protocol,priority:e.priority.toString(),connectionAddress:e.ip,port:e.port.toString(),type:e.type,extension:{}})));const r={fingerprints:e.dtlsParameters.fingerprints.map((e=>({hashFunction:e.algorithm,fingerprint:e.fingerprint})))},s={iceUfrag:e.iceParameters.iceUfrag,icePwd:e.iceParameters.icePwd};let o;switch(e.dtlsParameters.role){case\"server\":o=\"passive\";break;case\"client\":o=\"active\";break;case\"auto\":o=\"actpass\"}return{dtlsParameters:r,iceParameters:s,candidates:n,rtpCapabilities:Px(e.rtpCapabilities),setup:o,cname:i}}function Cx(e,t,i){const n=[],r=[];return e.forEach((e=>{let{ssrcId:s,rtx:o}=e;const a=nS(8,\"track-\"),c={ssrcId:s,attributes:fx({label:a,mslabel:i=i||nS(10,\"\"),msid:\"\".concat(i,\" \").concat(a)},t&&{cname:t})};if(n.push(c),void 0!==o){const e={ssrcId:o,attributes:fx({label:a,mslabel:i,msid:\"\".concat(i,\" \").concat(a)},t&&{cname:t})};n.push(e),r.push({semantic:\"FID\",ssrcIds:[s,o]})}})),e.length>1&&r.push({semantic:\"SIM\",ssrcIds:e.map((e=>{let{ssrcId:t}=e;return t}))}),{ssrcs:n,ssrcGroups:r}}function Ix(e,t){t instanceof ew&&e.attributes.payloads.forEach((e=>{var i;const n=null===(i=e.rtpMap)||void 0===i?void 0:i.encodingName.toLowerCase();if(!n||-1===[\"opus\",\"pcmu\",\"pcma\",\"g722\"].indexOf(n))return;e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters.minptime=\"10\",e.fmtp.parameters.useinbandfec=\"1\";const r=t._encoderConfig;r&&\"pcmu\"!==n&&\"pcma\"!==n&&\"g722\"!==n&&(r.bitrate&&!wg()&&(e.fmtp.parameters.maxaveragebitrate=\"\".concat(Math.floor(1e3*r.bitrate))),r.sampleRate&&(e.fmtp.parameters.maxplaybackrate=\"\".concat(r.sampleRate),e.fmtp.parameters[\"sprop-maxcapturerate\"]=\"\".concat(r.sampleRate)),r.stereo&&(e.fmtp.parameters.stereo=\"1\",e.fmtp.parameters[\"sprop-stereo\"]=\"1\"))}))}function vx(e){const t=e.attributes.unrecognized.findIndex((e=>\"x-google-flag\"===e.attField&&\"conference\"===e.attValue));-1!==t&&e.attributes.unrecognized.splice(t,1)}function yx(e,t){var i;if(!(t instanceof Rw&&t._encoderConfig&&-1===t._hints.indexOf(jA.SCREEN_TRACK)))return;const n=t._encoderConfig;IA().supportMinBitrate&&n.bitrateMin&&e.attributes.payloads.forEach((e=>{var t,i;bn(t=[\"h264\",\"h265\",\"vp8\",\"vp9\",\"av1\"]).call(t,(null===(i=e.rtpMap)||void 0===i?void 0:i.encodingName.toLowerCase())||\"\")&&(e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters[\"x-google-min-bitrate\"]=\"\".concat(n.bitrateMin))})),IA().supportMinBitrate&&!bn(i=t._hints).call(i,jA.LOW_STREAM)&&n.bitrateMax&&e.attributes.payloads.forEach((e=>{var t,i;bn(t=[\"h264\",\"h265\",\"vp8\",\"vp9\",\"av1\"]).call(t,(null===(i=e.rtpMap)||void 0===i?void 0:i.encodingName.toLowerCase())||\"\")&&(e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters[\"x-google-start-bitrate\"]=\"\".concat(RC(\"X_GOOGLE_START_BITRATE\")||Math.floor(n.bitrateMax)))}))}function Ax(e){if(\"video\"!==e.media.mediaType)return;const t=Sg();if(t.name!==Eg.SAFARI&&t.os!==_g.IOS)return;const i=e.attributes.extmaps.findIndex((e=>/video-orientation/g.test(e.extensionName)));-1!==i&&e.attributes.extmaps.splice(i,1)}function bx(e,t,i){if(!t)return;let n,r;if(\"video\"===e.media.mediaType?(n=i.videoExtensions,r=i.videoCodecs):(n=i.audioExtensions,r=i.audioCodecs),!0===t.twcc){const t=n.find((e=>\"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01\"===e.extensionName));if(t){e.attributes.extmaps.find((e=>\"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01\"===e.extensionName))||e.attributes.extmaps.push({entry:t.entry,extensionName:\"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01\"});const i=function(e,t){return t.filter((t=>!!e.find((e=>e.payloadType===t.payloadType&&!!e.rtcpFeedbacks.find((e=>\"transport-cc\"===e.type))))))}(r,e.attributes.payloads);i.forEach((e=>{e.rtcpFeedbacks.find((e=>\"transport-cc\"===e.type))||e.rtcpFeedbacks.push({type:\"transport-cc\"})}))}}else if(!1===t.twcc){const t=e.attributes.extmaps.findIndex((e=>\"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01\"===e.extensionName));-1!==t&&e.attributes.extmaps.splice(t,1),e.attributes.payloads.forEach((e=>{const t=e.rtcpFeedbacks.findIndex((e=>\"transport-cc\"===e.type));-1!==t&&e.rtcpFeedbacks.splice(t,1)}))}if(!0===t.remb){const t=n.find((e=>\"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time\"===e.extensionName));if(t){e.attributes.extmaps.find((e=>\"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time\"===e.extensionName))||e.attributes.extmaps.push({entry:t.entry,extensionName:\"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time\"});const i=function(e,t){return t.filter((t=>!!e.find((e=>e.payloadType===t.payloadType&&!!e.rtcpFeedbacks.find((e=>\"goog-remb\"===e.type))))))}(r,e.attributes.payloads);i.forEach((e=>{e.rtcpFeedbacks.find((e=>\"goog-remb\"===e.type))||e.rtcpFeedbacks.push({type:\"goog-remb\"})}))}}else if(!1===t.remb){const t=e.attributes.extmaps.findIndex((e=>\"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time\"===e.extensionName));-1!==t&&e.attributes.extmaps.splice(t,1),e.attributes.payloads.forEach((e=>{const t=e.rtcpFeedbacks.findIndex((e=>\"goog-remb\"===e.type));-1!==t&&e.rtcpFeedbacks.splice(t,1)}))}}function wx(e,t,i){if(wg())return;if(\"video\"!==e.media.mediaType)return;if(!(t instanceof Rw))return;if(\"vp9\"!==i&&\"vp8\"!==i)return;if(\"vp8\"===i&&!RC(\"SIMULCAST\"))return;if(void 0===t._scalabilityMode||t._scalabilityMode.numSpatialLayers<=1)return;const n=\"vp8\"===i?2:t._scalabilityMode.numSpatialLayers,r=e.attributes.ssrcs[0],s=e.attributes.ssrcGroups.find((e=>\"FID\"===e.semantic&&e.ssrcIds[0]===r.ssrcId)),o={semantic:\"SIM\",ssrcIds:[r.ssrcId]};for(let t=1;t0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i=new RTCPeerConnection;i.addTransceiver(\"video\",{direction:\"sendonly\"}),i.addTransceiver(\"audio\",{direction:\"sendonly\"}),i.addTransceiver(\"video\",{direction:\"recvonly\"}),i.addTransceiver(\"audio\",{direction:\"recvonly\"});const n=(await i.createOffer()).sdp,{send:r,recv:s,sendrecv:o}=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=arguments.length>2?arguments[2]:void 0;const n=gx(i,e,t,\"sendonly\"),r=gx(i,e,t,\"recvonly\"),s={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},o={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},a={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]};if(Dx(n,r,\"videoExtensions\",s,o,a),Dx(n,r,\"videoCodecs\",s,o,a),Dx(n,r,\"audioExtensions\",s,o,a),Dx(n,r,\"audioCodecs\",s,o,a),RC(\"RAISE_H264_BASELINE_PRIORITY\")){const e=a.videoCodecs.findIndex((e=>{var t,i;return\"h264\"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLocaleLowerCase())&&\"42001f\"===(null===(i=e.fmtp)||void 0===i?void 0:i.parameters[\"profile-level-id\"])}));if(-1!==e){const t=a.videoCodecs.findIndex((e=>{var t;return\"h264\"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLocaleLowerCase())}));if(t{var t,i;return!(\"h264\"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLocaleLowerCase())&&\"42001f\"!==(null===(i=e.fmtp)||void 0===i?void 0:i.parameters[\"profile-level-id\"]))}))),-1!==t&&RC(\"FILTER_SEND_H264_BASELINE\")&&(s.videoCodecs=s.videoCodecs.filter((e=>{var t,i;return!(\"h264\"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLocaleLowerCase())&&\"42001f\"!==(null===(i=e.fmtp)||void 0===i?void 0:i.parameters[\"profile-level-id\"]))})))}}return{send:s,recv:o,sendrecv:a}}(e,t,n);try{i.close()}catch(e){}return{send:r,recv:s,sendrecv:o}}function Nx(){const e={audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]},t=gx(arguments.length>2?arguments[2]:void 0,arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},\"recvonly\"),i={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},n={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},r={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]};if(Dx(e,t,\"videoExtensions\",i,n,r),Dx(e,t,\"videoCodecs\",i,n,r),Dx(e,t,\"audioExtensions\",i,n,r),Dx(e,t,\"audioCodecs\",i,n,r),RC(\"RAISE_H264_BASELINE_PRIORITY\")){const e=r.videoCodecs.findIndex((e=>e.rtpMap&&\"h264\"===e.rtpMap.encodingName.toLocaleLowerCase()&&e.fmtp&&\"42001f\"===e.fmtp.parameters[\"profile-level-id\"]));if(-1!==e){const t=r.videoCodecs.findIndex((e=>e.rtpMap&&\"h264\"===e.rtpMap.encodingName.toLocaleLowerCase()));if(t!(e.rtpMap&&\"h264\"===e.rtpMap.encodingName.toLocaleLowerCase()&&e.fmtp&&\"42001f\"!==e.fmtp.parameters[\"profile-level-id\"]))))}}return{send:i,recv:n,sendrecv:r}}function Dx(e,t,i,n,r,s){if(\"videoExtensions\"===i||\"audioExtensions\"===i){const o=[];return e[i].forEach((e=>{t[i].some(((t,i)=>{if(e.entry===t.entry&&e.extensionName===t.extensionName)return o.push(i),!0}))?s[i].push(e):n[i].push(e)})),void t[i].forEach(((e,t)=>{-1===o.indexOf(t)&&r[i].push(e)}))}if(\"videoCodecs\"===i||\"audioCodecs\"===i){const o=[];return e[i].forEach((e=>{t[i].some(((t,i)=>{if(e.payloadType===t.payloadType&&JSON.stringify(e)===JSON.stringify(t))return o.push(i),!0}))?s[i].push(e):n[i].push(e)})),void t[i].forEach(((e,t)=>{-1===o.indexOf(t)&&r[i].push(e)}))}}function Px(e){const{send:t,recv:i,sendrecv:n}=e;if(!n){if(!t||!i)throw new Error(\"cannot merge rtp capabilities because one of send or recv is empty!\");return{send:t,recv:i}}let r,s;return t?(r={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},r.audioCodecs=[...t.audioCodecs,...n.audioCodecs],r.videoCodecs=[...t.videoCodecs,...n.videoCodecs],r.audioExtensions=[...t.audioExtensions,...n.audioExtensions],r.videoExtensions=[...t.videoExtensions,...n.videoExtensions]):r=n,i?(s={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},s.audioCodecs=[...i.audioCodecs,...n.audioCodecs],s.videoCodecs=[...i.videoCodecs,...n.videoCodecs],s.audioExtensions=[...i.audioExtensions,...n.audioExtensions],s.videoExtensions=[...i.videoExtensions,...n.videoExtensions]):s=n,{send:r,recv:s}}function Lx(e){if(\"audio\"!==e.media.mediaType)return;e.attributes.payloads.filter((e=>{var t;return\"opus\"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())})).forEach((e=>{e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters.stereo=\"1\",e.fmtp.parameters[\"sprop-stereo\"]=\"1\"}))}function kx(e){e.mediaDescriptions.forEach((e=>{\"video\"!==e.media.mediaType&&\"audio\"!==e.media.mediaType||e.attributes.payloads.forEach((e=>{-1===e.rtcpFeedbacks.findIndex((e=>\"rrtr\"===e.type))&&e.rtcpFeedbacks.push({type:\"rrtr\"})}))}))}function Mx(e,t,i,n){let r=[];if(e===av.VIDEO){if(RC(\"H264_PROFILE_LEVEL_ID\")&&\"h264\"===n&&(r=t.videoCodecs.filter((e=>{var t;return bn(t=e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||\"\").call(t,n)&&e&&e.fmtp&&e.fmtp.parameters[\"profile-level-id\"]===RC(\"H264_PROFILE_LEVEL_ID\")}))),!Array.isArray(r)||0===r.length){let e=[];const s=[],o=[];i.videoCodecs.forEach((t=>{var i,r,a;bn(i=t.rtpMap&&t.rtpMap.encodingName.toLowerCase()||\"\").call(i,n)&&e.push(t),bn(r=t.rtpMap&&t.rtpMap.encodingName.toLowerCase()||\"\").call(r,\"vp8\")&&s.push(t),bn(a=t.rtpMap&&t.rtpMap.encodingName.toLowerCase()||\"\").call(a,\"h264\")&&o.push(t)})),0===e.length&&(0!==s.length?(e=s,jC.warning(\"codec \".concat(n,\" not included in rtpCapabilities, fallback to default payloads: vp8\"))):0!==o.length&&(e=o,jC.warning(\"codec \".concat(n,\" not included in rtpCapabilities, fallback to default payloads: h264\")))),0!==e.length&&(r=t.videoCodecs.filter((t=>e.some((e=>e.payloadType===t.payloadType)))))}if(RC(\"USE_PUB_RTX\")){const e=r.map((e=>e.payloadType.toString())),i=t.videoCodecs.filter((t=>t.rtpMap&&\"rtx\"===t.rtpMap.encodingName&&bn(e).call(e,t.fmtp&&t.fmtp.parameters.apt||\"\")));r=[...r,...i]}0===r.length&&(jC.warning(\"codec \".concat(n,\" not included in rtpCapabilities, fallback to default payloads: \").concat(t.videoCodecs[0].rtpMap&&t.videoCodecs[0].rtpMap.encodingName)),r=t.videoCodecs)}else r=t.audioCodecs.filter((e=>{var t;return bn(t=e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||\"\").call(t,n)})),0===r.length&&(jC.warning(\"codec \".concat(n,\" not included in rtpCapabilities, fallback to opus\")),r=t.audioCodecs.filter((e=>{var t;return bn(t=e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||\"\").call(t,\"opus\")})));return r}let Ux=class{get localCapabilities(){return YT(this._localCapabilities)}get rtpCapabilities(){return YT(this._rtpCapabilities)}get candidates(){return YT(this._candidates)}get iceParameters(){return YT(this._iceParameters)}get dtlsParameters(){return YT(this._dtlsParameters)}constructor(e){sh(this,\"sessionDesc\",void 0),sh(this,\"_localCapabilities\",void 0),sh(this,\"_rtpCapabilities\",void 0),sh(this,\"_candidates\",void 0),sh(this,\"_iceParameters\",void 0),sh(this,\"_dtlsParameters\",void 0),sh(this,\"setup\",void 0),sh(this,\"currentMidIndex\",void 0),sh(this,\"cname\",\"o/i14u9pJrxRKAsu\"),sh(this,\"firefoxSsrcMidMap\",new Map),e=YT(e);const{remoteIceParameters:t,remoteDtlsParameters:i,candidates:n,remoteRTPCapabilities:r,localCapabilities:s,direction:o,setup:a,videoCodec:c,audioCodec:d}=e;let l;this.setup=a,l=o===TI.RECEIVE_ONLY?JU.parse(\"v=0\\no=- 0 0 IN IP4 127.0.0.1\\ns=AgoraGateway\\nt=0 0\\na=group:BUNDLE 0 1\\na=msid-semantic: WMS\\na=extmap-allow-mixed\\nm=video 9 UDP/TLS/RTP/SAVPF 0\\nc=IN IP4 127.0.0.1\\na=rtcp:9 IN IP4 0.0.0.0\\na=sendonly\\na=rtcp-mux\\na=rtcp-rsize\\na=mid:0\\nm=audio 9 UDP/TLS/RTP/SAVPF 0\\nc=IN IP4 127.0.0.1\\na=rtcp:9 IN IP4 0.0.0.0\\na=sendonly\\na=rtcp-mux\\na=rtcp-rsize\\na=mid:1\\n\"):JU.parse(\"v=0\\no=- 0 0 IN IP4 127.0.0.1\\ns=AgoraGateway\\nt=0 0\\na=group:BUNDLE 0 1\\na=msid-semantic: WMS\\na=extmap-allow-mixed\\nm=video 9 UDP/TLS/RTP/SAVPF 0\\nc=IN IP4 127.0.0.1\\na=rtcp:9 IN IP4 0.0.0.0\\na=recvonly\\na=rtcp-mux\\na=rtcp-rsize\\na=mid:0\\nm=audio 9 UDP/TLS/RTP/SAVPF 0\\nc=IN IP4 127.0.0.1\\na=rtcp:9 IN IP4 0.0.0.0\\na=recvonly\\na=rtcp-mux\\na=rtcp-rsize\\na=mid:1\\n\"),this._rtpCapabilities=r,this._candidates=n,this._iceParameters=t,this._dtlsParameters=i,this._localCapabilities=s;const u=o===TI.RECEIVE_ONLY?this.rtpCapabilities.send:this.rtpCapabilities.recv,h=o===TI.RECEIVE_ONLY?this._localCapabilities.recv:this._localCapabilities.send,p=o===TI.RECEIVE_ONLY?r.send.videoCodecs:Mx(av.VIDEO,u,h,c),_=o===TI.RECEIVE_ONLY?r.send.audioCodecs:Mx(av.AUDIO,u,h,d);for(const e of l.mediaDescriptions){if(e.attributes.iceUfrag=t.iceUfrag,e.attributes.icePwd=t.icePwd,e.attributes.fingerprints=i.fingerprints,e.attributes.candidates=n,e.attributes.setup=this.setup,\"application\"===e.media.mediaType&&(e.attributes.sctpPort=\"5000\"),\"video\"===e.media.mediaType&&(e.media.fmts=p.map((e=>e.payloadType.toString(10))),e.attributes.payloads=p,e.attributes.extmaps=u.videoExtensions,RC(\"PRELOAD_MEDIA_COUNT\")>0)){const{ssrcs:t,ssrcGroups:i}=Cx([{ssrcId:4e4,rtx:RC(\"USE_SUB_RTX\")?40001:void 0}],this.cname);e.attributes.ssrcs=t,e.attributes.ssrcGroups=i}if(\"audio\"===e.media.mediaType&&(e.media.fmts=_.map((e=>e.payloadType.toString(10))),e.attributes.payloads=_,e.attributes.extmaps=u.audioExtensions,Lx(e),RC(\"PRELOAD_MEDIA_COUNT\")>0)){const{ssrcs:t,ssrcGroups:i}=Cx([{ssrcId:2e4}],this.cname);e.attributes.ssrcs=t,e.attributes.ssrcGroups=i}}this.sessionDesc=l,this.currentMidIndex=l.mediaDescriptions.length-1}toString(){return JU.print(this.sessionDesc)}hasMid(e){return Array.isArray(e)?e.every((e=>this.hasMid(e))):this.sessionDesc.mediaDescriptions.some((t=>t.attributes.mid===e))}send(e,t,i,n,r){i=i.replace(/ /g,\"-\");const{ssrcs:s,ssrcGroups:o}=Cx(t,this.cname,RC(\"SYNC_GROUP\")?i:void 0),a=this.findPreloadMediaDesc(s);if(a){if(wg()&&this.firefoxSsrcMidMap.set(s[0].ssrcId,a.attributes.mid),r&&(r.twcc||r.remb)){const e=this.sessionDesc.mediaDescriptions.indexOf(a);return this.sessionDesc.mediaDescriptions[e]=this.mungSendMediaDesc(a,r),{mid:a.attributes.mid,needExchangeSDP:!0}}return{mid:a.attributes.mid,needExchangeSDP:!1}}{const t=this.findAvailableMediaIndex(e,s,n);let i;return-1===t?(i=this.createOrRecycleSendMedia(e,s,o,\"sendonly\",n,r),this.updateBundleMids()):(i=YT(this.sessionDesc.mediaDescriptions[t]),i.attributes.direction=\"sendonly\",i.attributes.ssrcs=s,i.attributes.ssrcGroups=o,this.sessionDesc.mediaDescriptions[t]=this.mungSendMediaDesc(i,r)),wg()&&this.firefoxSsrcMidMap.set(s[0].ssrcId,i.attributes.mid),{needExchangeSDP:!0,mid:i.attributes.mid}}}stopSending(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>t.attributes.mid&&-1!==e.indexOf(t.attributes.mid)));if(t.length!==e.length)throw new Error(\"mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.stopSending.\");t.forEach((e=>{e.attributes.ssrcs=[]})),this.updateBundleMids()}receive(e,t,i){const n=[];return e.forEach((e=>{const r=e._mediaStreamTrack.kind,s=this.findAvailableRecvMediaIndex(r);let o,a=!1;-1===s?(a=!0,o=this.createOrRecycleRecvMedia(e,[],\"recvonly\",t,i),this.updateBundleMids()):(o=YT(this.sessionDesc.mediaDescriptions[s]),o.attributes.direction=\"recvonly\"),n.push({mid:o.attributes.mid,needCreateTransceiver:a})})),n}stopReceiving(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>-1!==e.indexOf(t.attributes.mid)));if(t.length!==e.length)throw new Error(\"MediaDescriptions' length doesn't match mids's length when calling RemoteSDP.receive.\");t.forEach((e=>{e.media.port=\"0\",e.attributes.direction=\"inactive\"})),this.updateBundleMids()}addRemoteCandidate(e){const{foundation:t,protocol:i,address:n,port:r,type:s,relatedAddress:o,relatedPort:a,priority:c}=new RTCIceCandidate(e),d={foundation:null!=t?t:\"\",componentId:\"1\",transport:null!=i?i:\"\",priority:c?c+\"\":\"\",connectionAddress:null!=n?n:\"\",port:r?r+\"\":\"\",type:s?s+\"\":\"\",relAddr:null!=o?o:\"\",relPort:a?a+\"\":\"\",extension:{}};this.candidates.some((e=>e.priority===d.priority&&e.connectionAddress===d.connectionAddress&&e.port===d.port))||(this._candidates.push(d),this.sessionDesc.mediaDescriptions.forEach((e=>{e.attributes.candidates=this.candidates})))}clearRemoteCandidate(){this._candidates=[],this.sessionDesc.mediaDescriptions[0].attributes.candidates=this._candidates}createOrRecycleRecvMedia(e,t,i,n,r){const s=e._mediaStreamTrack.kind,o=this.rtpCapabilities.recv,a=Mx(s,o,this.localCapabilities.send,s===av.AUDIO?r:n),c=s===av.VIDEO?o.videoExtensions:o.audioExtensions,d=\"\".concat(++this.currentMidIndex);let l={media:{mediaType:s,port:\"9\",protos:[\"UDP\",\"TLS\",\"RTP\",\"SAVPF\"],fmts:a.map((e=>e.payloadType.toString(10)))},connections:[{nettype:\"IN\",addrtype:\"IP4\",address:\"127.0.0.1\"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:[],extmaps:c,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:a,rtcp:{port:\"9\",netType:\"IN\",addressType:\"IP4\",address:\"0.0.0.0\"},setup:this.setup,direction:i,rtcpMux:!0,rtcpRsize:!0,mid:\"\".concat(d)}};l=this.mungRecvMediaDsec(l,e);const u=this.findFirstClosedMedia(s);if(u){const e=this.sessionDesc.mediaDescriptions.indexOf(u);this.sessionDesc.mediaDescriptions[e]=l}else this.sessionDesc.mediaDescriptions.push(l);return l}muteRemote(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>bn(e).call(e,t.attributes.mid||\"\")));if(t.length!==e.length)throw new Error(\"mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.\");t.forEach((e=>{e.attributes.direction=\"inactive\"}))}unmuteRemote(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>bn(e).call(e,t.attributes.mid||\"\")));if(t.length!==e.length)throw new Error(\"mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.\");t.forEach((e=>{e.attributes.direction=\"recvonly\"}))}findAvailableMediaIndex(e,t,i){return this.sessionDesc.mediaDescriptions.findIndex((n=>{const r=n.media.mediaType===e&&\"0\"!==n.media.port&&(\"sendonly\"===n.attributes.direction||\"sendrecv\"===n.attributes.direction)&&0===n.attributes.ssrcs.length;if(wg()){if(r){const e=this.firefoxSsrcMidMap.get(t[0].ssrcId);return!(e||\"0\"!==n.attributes.mid&&\"1\"!==n.attributes.mid)||!(!e||e!==n.attributes.mid)}return!1}return r&&n.attributes.mid===i}))}findAvailableRecvMediaIndex(e){return this.sessionDesc.mediaDescriptions.findIndex((t=>{const i=t.media.mediaType===e&&\"0\"!==t.media.port&&(\"recvonly\"===t.attributes.direction||\"sendrecv\"===t.attributes.direction);return\"0\"!==t.attributes.mid&&\"1\"!==t.attributes.mid&&i}))}predictReceivingMids(e){const t=[];for(let i=0;i{t.attributes.iceUfrag=e.iceUfrag,t.attributes.icePwd=e.icePwd}))}createOrRecycleSendMedia(e,t,i,n,r,s){const o=this.rtpCapabilities.send,a=e===av.VIDEO?o.videoCodecs:o.audioCodecs,c=e===av.VIDEO?o.videoExtensions:o.audioExtensions;wg()&&(r=\"\".concat(++this.currentMidIndex));let d={media:{mediaType:e,port:\"9\",protos:[\"UDP\",\"TLS\",\"RTP\",\"SAVPF\"],fmts:a.map((e=>e.payloadType.toString(10)))},connections:[{nettype:\"IN\",addrtype:\"IP4\",address:\"127.0.0.1\"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:[],extmaps:c,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:i,rtcpFeedbackWildcards:[],payloads:a,rtcp:{port:\"9\",netType:\"IN\",addressType:\"IP4\",address:\"0.0.0.0\"},setup:this.setup,direction:n,rtcpMux:!0,rtcpRsize:!0,mid:r}};d=this.mungSendMediaDesc(d,s);const l=this.findFirstClosedMedia(e);if(l){const e=this.sessionDesc.mediaDescriptions.indexOf(l);this.sessionDesc.mediaDescriptions[e]=d}else this.sessionDesc.mediaDescriptions.push(d);return d}mungRecvMediaDsec(e,t,i){const n=YT(e);return vx(n),Ix(n,t),yx(n,t),Ax(n),bx(n,i,this.localCapabilities.send),n}mungSendMediaDesc(e,t){const i=YT(e);return bx(i,t,this.localCapabilities.recv),Lx(i),i}updateRecvMedia(e,t){const i=this.sessionDesc.mediaDescriptions.findIndex((t=>t.attributes.mid===e));if(-1!==i){const e=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[i],t);this.sessionDesc.mediaDescriptions[i]=e}}updateBundleMids(){this.sessionDesc.attributes.groups[0].identificationTag=this.sessionDesc.mediaDescriptions.filter((e=>\"0\"!==e.media.port)).map((e=>e.attributes.mid))}findPreloadMediaDesc(e){return this.sessionDesc.mediaDescriptions.find((t=>{var i;return(null===(i=t.attributes)||void 0===i||null===(i=i.ssrcs[0])||void 0===i?void 0:i.ssrcId)===e[0].ssrcId}))}findFirstClosedMedia(e){return this.sessionDesc.mediaDescriptions.find((t=>wg()?\"0\"===t.media.port&&t.media.mediaType===e:\"0\"===t.media.port))}};const xx=[\"sdp\"];function Vx(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function Fx(e){for(var t=1;t2?arguments[2]:void 0,arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},\"sendonly\"),i={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},n={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},r={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]};if(Dx(t,e,\"videoExtensions\",i,n,r),Dx(t,e,\"videoCodecs\",i,n,r),Dx(t,e,\"audioExtensions\",i,n,r),Dx(t,e,\"audioCodecs\",i,n,r),RC(\"RAISE_H264_BASELINE_PRIORITY\")){const e=r.videoCodecs.findIndex((e=>e.rtpMap&&\"h264\"===e.rtpMap.encodingName.toLocaleLowerCase()&&e.fmtp&&\"42001f\"===e.fmtp.parameters[\"profile-level-id\"]));if(-1!==e){const t=r.videoCodecs.findIndex((e=>e.rtpMap&&\"h264\"===e.rtpMap.encodingName.toLocaleLowerCase()));if(t!(e.rtpMap&&\"h264\"===e.rtpMap.encodingName.toLocaleLowerCase()&&e.fmtp&&\"42001f\"!==e.fmtp.parameters[\"profile-level-id\"]))))}}return{send:i,recv:n,sendrecv:r}}(this.filter,this.extension,t);this.remoteSDP=new Ux({remoteIceParameters:i.iceParameters,remoteDtlsParameters:i.dtlsParameters,candidates:[],remoteRTPCapabilities:n,localCapabilities:this.localCapabilities,direction:this.direction,setup:\"actpass\",videoCodec:this.store.codec,audioCodec:this.store.audioCodec}),await this.setRemoteDescription({type:\"offer\",sdp:this.remoteSDP.toString()}),this.isReady=!0;const r=await this.peerConnection.createAnswer();if(!r.sdp)throw new Error(\"Cannot get answer sdp when trying to establish PeerConnection.\");const s=Tx(r.sdp);await this.peerConnection.setLocalDescription(r);const o=await Nx(this.filter,this.extension,r.sdp);this.localCapabilities=Px(o);const a=this.peerConnection.getTransceivers()[0];return null!=a&&a.receiver&&a.receiver.transport&&this.tryBindTransportEvents(a.receiver.transport),Fx(Fx({},s),{},{sdp:r.sdp})}{this.peerConnection.addTransceiver(\"video\",{direction:\"sendonly\"}),this.peerConnection.addTransceiver(\"audio\",{direction:\"sendonly\"});const e=await this.peerConnection.createOffer();if(!e.sdp)throw new Error(\"Cannot get initialOffer.sdp when trying to establish PeerConnection.\");const t=Tx(e.sdp);return this.initialOffer=e,Fx(Fx({},t),{},{sdp:e.sdp})}}catch(e){throw new Kg(Hg.GET_LOCAL_CONNECTION_PARAMS_FAILED,e.toString())}}async connect(e){try{if(!this.initialOffer)throw new Error(\"Cannot establish P2PConnection without initial offer.\");await this.peerConnection.setLocalDescription(this.initialOffer);const{sdp:t,iceParameters:i,dtlsParameters:n}=e,r=await Nx(this.filter,this.extension,t);this.remoteSDP=new Ux({remoteIceParameters:i,remoteDtlsParameters:n,candidates:[],remoteRTPCapabilities:r,localCapabilities:this.localCapabilities,direction:this.direction,setup:\"active\",videoCodec:this.store.codec,audioCodec:this.store.audioCodec}),await this.setRemoteDescription({type:\"answer\",sdp:this.remoteSDP.toString()});const s=this.peerConnection.getTransceivers()[0];null!=s&&s.sender&&s.sender.transport&&this.tryBindTransportEvents(s.sender.transport)}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,\"P2PConnection.connect failed; \".concat(e.toString()))}}async addRemoteCandidate(e){try{e&&this.pendingCandidates.push(e),this.peerConnection.remoteDescription&&this.isReady&&(this.pendingCandidates.forEach((e=>{this.peerConnection.addIceCandidate(e)})),this.pendingCandidates=[])}catch(e){throw new Kg(Hg.ADD_CANDIDATE_FAILED,\"P2PConnection.addRemoteCandidate failed; \".concat(e.toString()))}}send(e,t,i){var n=this;return PU((function*(){const r=yield IU(n.mutex.lock(\"From P2PConnection.send\"));try{if(!n.remoteSDP)throw new Error(\"Cannot call P2PConnection.send before remote SDP created\");const s=[],o=n.remoteSDP.receive(e,t,i);e.forEach(((e,t)=>{if(o[t].needCreateTransceiver){const t=n.peerConnection.addTransceiver(e._mediaStreamTrack,{direction:\"sendonly\"});s.push(t),e._updateRtpTransceiver(t)}else{const i=n.peerConnection.getTransceivers().find((e=>e.mid===o[t].mid));if(!i)throw new Error(\"cannot find transceiver when sendPeerconnection send, mid is \".concat(o[t].mid));s.push(i),e._updateRtpTransceiver(i)}})),wg()&&!0===RC(\"SIMULCAST\")&&(yield IU(n.applySimulcastForFirefox(s,e)));const a=o.map((e=>e.mid)),c=yield IU(n.peerConnection.createOffer()),d=n.mungSendOfferSDP(c.sdp,e,a),l=JU.parse(d),u=a.map((e=>{const t=l.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error(\"Cannot extract ssrc from mediaDescription.\");return Sx(t,RC(\"USE_PUB_RTX\"))})),h=s.map(((e,t)=>{const i=a[t];return{localSSRC:u[t],id:i}}));yield IU(n.peerConnection.setLocalDescription({type:\"offer\",sdp:d}));try{yield h}catch(e){const t=n.remoteSDP.toString();throw yield IU(n.peerConnection.setLocalDescription({type:\"offer\",sdp:d})),yield IU(n.peerConnection.setRemoteDescription({type:\"answer\",sdp:t})),yield IU(n.stopSending(a,!0)),e}yield IU(n.applySimulcastEncodings(s,e)),yield IU(n.applySendEncodings(s,e));const p=n.remoteSDP.toString(),_=n.logSDPExchange(d,\"offer\",\"local\",\"send\");return null==_||_(p),yield IU(n.setRemoteDescription({type:\"answer\",sdp:p})),s.map(((e,t)=>{const i=a[t];return{localSSRC:u[t],id:i}}))}catch(e){throw e instanceof Kg?e:new Kg(Hg.EXCHANGE_SDP_FAILED,\"P2PConnection.send failed; \".concat(e.toString()))}finally{r()}}))()}async stopSending(e,t){const i=t?void 0:await this.mutex.lock(\"From P2PConnection.stopSending\");try{if(!this.remoteSDP)throw new Error(\"Cannot call P2PConnection.stopSending before remote SDP created\");const t=this.peerConnection.getTransceivers().filter((t=>-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error(\"Transceivers' length (\".concat(t.length,\") doesn't match mids' length (\").concat(e.length,\") when trying to call P2PConnection.stopSending.\"));t.map((e=>{var t;e.direction=\"inactive\",null===(t=e.stop)||void 0===t||t.call(e)}));const n=await this.peerConnection.createOffer(),r=this.logSDPExchange(n.sdp||\"\",\"offer\",\"local\",\"stopSending\");await this.peerConnection.setLocalDescription(n),this.remoteSDP.stopReceiving(e);const s=this.remoteSDP.toString();null==r||r(s),await this.setRemoteDescription({type:\"answer\",sdp:s})}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,\"P2PConnection.stopSending failed; \".concat(e.toString()))}finally{i&&i()}}async receive(e,t,i,n){try{if(!this.remoteSDP)throw new Error(\"Cannot call P2PConnection.receive \".concat(e,\" before remoteSDP created.\"));const{mid:r,needExchangeSDP:s}=this.remoteSDP.send(e,t,i,n);if(s){const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,\"offer\",\"remote\",\"receive\");await this.setRemoteDescription({type:\"offer\",sdp:t});const n=await this.peerConnection.createAnswer(),s=this.mungReceiveAnswerSDP(n.sdp,r,e);null==i||i(s||\"\"),await this.peerConnection.setLocalDescription({type:\"answer\",sdp:s}),jC.debug(\"[\".concat(this.store.clientId,\"] [P2PConnection] receive \").concat(e,\" by exchanging SDP.\"))}else jC.debug(\"[\".concat(this.store.clientId,\"] [P2PConnection] receive \").concat(e,\" no need to exchange SDP.\"));const o=this.peerConnection.getTransceivers().find((e=>e.mid===r));if(!o||null===o.mid)throw new Error(\"Cannot get transceiver after setLocalDescription.\");return{track:o.receiver.track,mid:o.mid,transceiver:o}}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,\"P2PConnection.receive failed; \".concat(e.toString()))}}async mockReceive(e,t,i,n){try{if(!this.remoteSDP)throw new Error(\"Cannot call P2PConnection.receive \".concat(e,\" before remoteSDP created.\"));const{mid:r,needExchangeSDP:s}=this.remoteSDP.send(e,t,i,n);if(s){const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,\"offer\",\"remote\",\"receive\");await this.setRemoteDescription({type:\"offer\",sdp:t});const n=await this.peerConnection.createAnswer(),s=this.mungReceiveAnswerSDP(n.sdp,r,e);null==i||i(s||\"\"),await this.peerConnection.setLocalDescription({type:\"answer\",sdp:s}),jC.debug(\"[\".concat(this.store.clientId,\"] [P2PConnection] receive \").concat(e,\" by exchanging SDP.\"))}else jC.debug(\"[\".concat(this.store.clientId,\"] [P2PConnection] receive \").concat(e,\" no need to exchange SDP.\"))}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,\"P2PConnection.receive failed; \".concat(e.toString()))}}async stopReceiving(e){try{if(!this.remoteSDP)throw new Error(\"Cannot call P2PConnection.stopReceiving before remote SDP created.\");this.remoteSDP.stopSending(e);const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,\"offer\",\"remote\",\"stopReceiving\");await this.setRemoteDescription({type:\"offer\",sdp:t});const n=await this.peerConnection.createAnswer();null==i||i(n.sdp||\"\"),await this.peerConnection.setLocalDescription(n)}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,\"P2PConnection stopReceiving failed; \".concat(e.toString()))}}async restartICE(t){try{if(this.store.p2pTransport===fC.Auto&&(this.store.p2pTransport=fC.SdRtn,IA().supportPCSetConfiguration&&this.peerConnection.setConfiguration(e.resolvePCConfiguration(this.spec,this.store.p2pTransport))),this.restartCnt>3&&(this.restartCnt=0,IA().supportPCSetConfiguration&&this.peerConnection.setConfiguration(e.resolvePCConfiguration(this.spec,this.store.p2pTransport,++this.curTurnServerIndex))),!t){this.restartCnt++,this.isReady=!1;const e=await this.peerConnection.createOffer({iceRestart:!0});if(!e.sdp)throw new Error(\"Cannot restartICE because restart offer SDP does not exist.\");const{iceParameters:t}=Tx(e.sdp);return this.store.descriptionStart(),this.direction===TI.SEND_ONLY&&await this.peerConnection.setLocalDescription(e),t}if(!this.remoteSDP)throw new Error(\"Cannot call P2PConnection.stopReceiving before remote SDP created.\");if(this.remoteSDP.restartICE(t),this.store.descriptionStart(),this.direction===TI.RECEIVE_ONLY){this.restartCnt++,await this.setRemoteDescription({type:\"offer\",sdp:this.remoteSDP.toString()});const e=await this.peerConnection.createAnswer();if(!e.sdp)throw new Error(\"Cannot get answer sdp when trying to iceRestart.\");const{iceParameters:t}=Tx(e.sdp);return await this.peerConnection.setLocalDescription(e),t}await this.setRemoteDescription({type:\"answer\",sdp:this.remoteSDP.toString()}),this.isReady=!0}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,\"P2PConnection stopReceiving failed; \".concat(e.toString()))}}close(){var e;this.peerConnection.close(),this.peerConnection.onicecandidate=null,null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,\"closed\"),this.tryUnbindTransportEvents(),this.unbindPCEvents(),this.unbindStatsEvents(),this.transport=void 0,this.statsFilter.destroy()}getStats(){return this.statsFilter.getStats()}getRemoteVideoIsReady(e){return this.statsFilter.getVideoIsReady(e)}async updateEncoderConfig(e,t){try{if(!this.remoteSDP)throw new Error(\"Cannot call P2PConnection.updateEncoderConfig before remote SDP created.\");const i=await this.peerConnection.createOffer(),n=this.mungSendOfferSDP(i.sdp,[t],[e]);this.remoteSDP.updateRecvMedia(e,t);const r=this.remoteSDP.toString(),s=this.logSDPExchange(n,\"offer\",\"local\",\"updateEncoderConfig\");await this.peerConnection.setLocalDescription({type:\"offer\",sdp:n}),null==s||s(r),await this.peerConnection.setRemoteDescription({type:\"answer\",sdp:r})}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,e.toString())}}async updateSendParameters(e,t){const i=this.peerConnection.getTransceivers().filter((t=>t.mid===e));1===i.length&&(this.isVP8Simulcast(t)?wg()||await this.applySimulcastEncodings(i,[t]):await this.applySendEncodings(i,[t]))}setStatsRemoteVideoIsReady(e,t){this.statsFilter.setVideoIsReady2(e,t)}async replaceTrack(e,t){const i=this.peerConnection.getTransceivers().find((e=>e.mid===t));i&&await i.sender.replaceTrack(e._mediaStreamTrack)}async getSelectedCandidatePair(){const e=this.peerConnection.getReceivers();if(e.length>0&&e[0].transport&&e[0].transport.iceTransport&&e[0].transport.iceTransport.getSelectedCandidatePair&&e[0].transport.iceTransport.getSelectedCandidatePair()){const t=e[0].transport.iceTransport,{local:i,remote:n}=t.getSelectedCandidatePair();return{local:Fx(Fx({},$U),{},{candidateType:i.type,protocol:i.protocol,address:i.address,port:i.port}),remote:Fx(Fx({},$U),{},{candidateType:n.type,protocol:n.protocol,address:n.address,port:n.port})}}return this.statsFilter.getSelectedCandidatePair()}bindPCEvents(){this.peerConnection.oniceconnectionstatechange=()=>{var e,t;bn(e=[\"connected\",\"completed\"]).call(e,this.peerConnection.iceConnectionState)&&(this.isReady=!1),null===(t=this.onICEConnectionStateChange)||void 0===t||t.call(this,this.peerConnection.iceConnectionState)},this.peerConnection.onconnectionstatechange=()=>{var e;\"connected\"===this.peerConnection.connectionState&&(this.restartCnt=0),null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.connectionState)},this.startICECandidate()}startICECandidate(){this.peerConnection.onicecandidate||(this.localCandidateCount=0,this.peerConnection.onicecandidate=e=>{if(e.candidate){var t;if(e.candidate.candidate)this.localCandidateAddress=e.candidate.address,null===(t=this.onLocalCandidate)||void 0===t||t.call(this,e.candidate.toJSON());this.localCandidateCount+=1}else this.allCandidatesReceived=!0,jC.debug(\"[\".concat(this.store.clientId,\"] [pc-\").concat(this.store.p2pId,\"] local candidate count\"),this.localCandidateCount)})}unbindPCEvents(){this.peerConnection.oniceconnectionstatechange=null,this.peerConnection.onconnectionstatechange=null,this.peerConnection.onsignalingstatechange=null,this.peerConnection.onicecandidateerror=null,this.peerConnection.onicecandidate=null,this.peerConnection.ontrack=null}static resolvePCConfiguration(t,i){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;const r={iceServers:[]};var s;t.iceServers?r.iceServers=t.iceServers:t.turnServer&&\"off\"!==t.turnServer.mode&&(RT(t.turnServer.servers)?r.iceServers=t.turnServer.servers:(r.iceServers&&r.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers,i,n)),RC(\"USE_TURN_SERVER_OF_GATEWAY\")&&r.iceServers&&t.turnServer.serversFromGateway&&r.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.serversFromGateway,i,n)),bn(s=[fC.Relay,fC.SdRtn]).call(s,i)&&(r.iceTransportPolicy=\"relay\"),RC(\"FORCE_TURN_TCP\")?r.iceTransportPolicy=\"relay\":t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEach((e=>{e.forceturn&&(r.iceTransportPolicy=\"relay\")}))));return RC(\"ENABLE_ENCODED_TRANSFORM\")&&IA().supportWebRTCEncodedTransform&&(r.encodedInsertableStreams=!0),jC.debug(\"P2PConnection p2pTransport is \".concat(i)),r}static turnServerConfigToIceServers(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;const n=[],r=e.filter((e=>e.tcpport));jC.debug(\"P2PConnection turnServers is \".concat(r,\", current index is \").concat(i));const s=r.length>i?r[i]:r[0];switch(t){case fC.SdRtn:const t=e.filter((e=>{var t;return bn(t=e.username).call(t,\"glb:\")&&e.turnServerURL==e.turnServerURL})),r=t.length>i?t[i]:t[0];r&&(n.push({username:r.username,credential:r.password,credentialType:\"password\",urls:\"turn:\".concat(gy(r.turnServerURL),\":\").concat(r.tcpport,\"?transport=udp\")}),n.push({username:r.username,credential:r.password,credentialType:\"password\",urls:\"turns:\".concat(gy(r.turnServerURL),\":\").concat(r.tcpport,\"?transport=tcp\")}));break;case fC.Relay:s&&(n.push({username:s.username,credential:s.password,credentialType:\"password\",urls:\"turn:\".concat(s.turnServerURL,\":\").concat(s.tcpport,\"?transport=udp\")}),n.push({username:s.username,credential:s.password,credentialType:\"password\",urls:\"turns:\".concat(gy(s.turnServerURL),\":\").concat(s.tcpport,\"?transport=tcp\")}));break;default:s&&(n.push({username:s.username,credential:s.password,credentialType:\"password\",urls:\"turn:\".concat(s.turnServerURL,\":\").concat(s.tcpport,\"?transport=udp\")}),n.push({username:s.username,credential:s.password,credentialType:\"password\",urls:\"turns:\".concat(gy(s.turnServerURL),\":\").concat(s.tcpport,\"?transport=tcp\")}),n.push({username:s.username,credential:s.password,credentialType:\"password\",urls:\"stun:\".concat(s.turnServerURL,\":\").concat(s.tcpport)}))}return n}tryBindTransportEvents(e){if(e){this.transport=e,e.onstatechange=()=>{var t;null!=e&&e.state&&(null===(t=this.onDTLSTransportStateChange)||void 0===t||t.call(this,e.state))},e.onerror=e=>{var t;null===(t=this.onDTLSTransportError)||void 0===t||t.call(this,\"error\"in e?e.error:e)};const t=e.iceTransport;t&&(t.onstatechange=()=>{const t=null==e?void 0:e.iceTransport.state;var i;t&&(null===(i=this.onICETransportStateChange)||void 0===i||i.call(this,t))},t.getSelectedCandidatePair&&(t.onselectedcandidatepairchange=()=>{if(t.getSelectedCandidatePair()){const{local:e,remote:i}=t.getSelectedCandidatePair();jC.info(\"[\".concat(this.store.clientId,\"] [pc-\").concat(this.store.p2pId,\"] selectedcandidatepairchange: local \").concat(JSON.stringify({candidateType:e.type,protocol:e.protocol}),\", remote \").concat(JSON.stringify({candidateType:i.type,protocol:i.protocol,address:i.address,port:i.port}),\" )\"))}}))}}tryUnbindTransportEvents(){this.transport&&(this.transport.onstatechange=null,this.transport.onerror=null,this.transport.iceTransport&&(this.transport.iceTransport.onstatechange=null))}async updateRtpSenderEncodings(e,t){var i;if(!t){t=this.peerConnection.getSenders().find((t=>t.track===e._mediaStreamTrack))}if(!t)return jC.warn(\"[\".concat(e.getTrackId(),\"] no rtpSender found}\"));if(this.isVP8Simulcast(e))return jC.warn(\"[updateRtpSenderEncodings] Track is VP8 simulcast, please apply simulcast encodings\");if(!IA().supportSetRtpSenderParameters)return jC.warn(\"[updateRtpSenderEncodings] Browser not support set rtp-sender parameters\");const n={},r={};switch(e._optimizationMode){case\"motion\":n.degradationPreference=\"maintain-framerate\";break;case\"detail\":n.degradationPreference=\"maintain-resolution\";break;default:n.degradationPreference=\"balanced\"}if(e._encoderConfig){var s;const{bitrateMax:t,frameRate:i,scaleResolutionDownBy:n}=e._encoderConfig;t&&(r.maxBitrate=1e3*t),bn(s=e._hints).call(s,jA.LOW_STREAM)&&(i&&(r.maxFramerate=Sy(i)),n&&n>=1&&(r.scaleResolutionDownBy=n))}if(RC(\"DSCP_TYPE\")&&jg()){var o;const e=RC(\"DSCP_TYPE\");bn(o=[\"very-low\",\"low\",\"medium\",\"high\"]).call(o,e)&&(r.networkPriority=e)}const a=t.getParameters(),c=null===(i=a.encodings)||void 0===i?void 0:i[0];wg()&&!c&&(n.encodings=[r]),c&&Object.assign(c,r),Object.assign(a,n),jC.debug(\"[\".concat(e.getTrackId(),\"] updateRtpSenderEncodings: \").concat(JSON.stringify(a.encodings))),await t.setParameters(a)}async applySendEncodings(e,t){try{if(!IA().supportSetRtpSenderParameters)return;if(e.length!==t.length)return;for(let i=0;i{const r=i[t],s=n.mediaDescriptions.find((e=>e.attributes.mid===r));s&&(Ix(s,e),wx(s,e,this.store.codec))})),JU.print(n)}bindStatsEvents(){this.statsFilter.onFirstAudioReceived=e=>{var t;null===(t=this.onFirstAudioReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoReceived=e=>{var t;null===(t=this.onFirstVideoReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstAudioDecoded=e=>{var t;null===(t=this.onFirstAudioDecoded)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoDecoded=(e,t,i)=>{var n;null===(n=this.onFirstVideoDecoded)||void 0===n||n.call(this,e,t,i)},this.statsFilter.onSelectedLocalCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedLocalCandidateChanged)||void 0===i||i.call(this,e,t)},this.statsFilter.onSelectedRemoteCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedRemoteCandidateChanged)||void 0===i||i.call(this,e,t)},this.statsFilter.onFirstVideoDecodedTimeout=e=>{var t;null===(t=this.onFirstVideoDecodedTimeout)||void 0===t||t.call(this,e)}}unbindStatsEvents(){this.statsFilter.onFirstAudioReceived=void 0,this.statsFilter.onFirstVideoReceived=void 0,this.statsFilter.onFirstAudioDecoded=void 0,this.statsFilter.onFirstVideoDecoded=void 0,this.statsFilter.onSelectedLocalCandidateChanged=void 0,this.statsFilter.onSelectedRemoteCandidateChanged=void 0,this.statsFilter.onFirstVideoDecodedTimeout=void 0}async applySimulcastForFirefox(e,t){if(e.length===t.length)for(let a=0;a200&&null!==(s=d._scalabilityMode)&&void 0!==s&&s.numSpatialLayers&&(null===(o=d._scalabilityMode)||void 0===o?void 0:o.numSpatialLayers)>1&&\"vp8\"===this.store.codec){const e={},t={high:1e3*(d._encoderConfig.bitrateMax-50),medium:5e4};e.encodings=[{rid:\"m\",active:!0,maxBitrate:t.medium,scaleResolutionDownBy:4},{rid:\"h\",active:!0,maxBitrate:t.high}];const i=c.sender.getParameters();await c.sender.setParameters(Object.assign(i,e))}}}async applySimulcastEncodings(e,t){if(!wg()&&e.length===t.length)for(let i=0;i200&&null!==(r=e._scalabilityMode)&&void 0!==r&&r.numSpatialLayers&&(null===(s=e._scalabilityMode)||void 0===s?void 0:s.numSpatialLayers)>1)}logSDPExchange(e,t,i,n){if(RC(\"SDP_LOGGING\"))return jC.upload(\"[\".concat(this.store.clientId,\"] exchanging \").concat(i,\" \").concat(t,\" SDP during P2PConnection.\").concat(n,\"\\n\"),e),\"offer\"===t?e=>{this.logSDPExchange(e,\"answer\",\"local\"===i?\"remote\":\"local\",n)}:void 0}async muteLocal(e){try{if(!this.remoteSDP)throw new Error(\"Cannot call P2PConnection.muteLocal before remote SDP created.\");const t=this.peerConnection.getTransceivers().filter((t=>t.mid&&-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error(\"Transceivers' length doesn't match mids' length.\");t.map((e=>{e.direction=\"inactive\"}));const i=await this.peerConnection.createOffer(),n=this.logSDPExchange(i.sdp||\"\",\"offer\",\"local\",\"muteLocal\");await this.peerConnection.setLocalDescription(i),this.remoteSDP.muteRemote(e);const r=this.remoteSDP.toString();null==n||n(r),await this.setRemoteDescription({type:\"answer\",sdp:r})}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,\"P2PConnection.muteLocal failed; \".concat(e.toString()))}}async unmuteLocal(e){try{if(!this.remoteSDP)throw new Error(\"Cannot call P2PConnection.unmuteLocal before remote SDP created.\");const t=this.peerConnection.getTransceivers().filter((t=>t.mid&&-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error(\"Transceivers' length doesn't match mids' length.\");t.map((async e=>{e.direction=\"sendonly\"}));const i=await this.peerConnection.createOffer(),n=this.logSDPExchange(i.sdp||\"\",\"offer\",\"local\",\"unmuteLocal\");await this.peerConnection.setLocalDescription(i),this.remoteSDP.unmuteRemote(e);const r=this.remoteSDP.toString();null==n||n(r),await this.setRemoteDescription({type:\"answer\",sdp:r})}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,\"P2PConnection.unmuteLocal failed; \".concat(e.toString()))}}async getRemoteSSRC(e,t){var i,n;if(t=null!==(i=t)&&void 0!==i?i:null===(n=this.currentRemoteDescription)||void 0===n?void 0:n.sdp){var r;const i=null===(r=JU.parse(t).mediaDescriptions.find((t=>t.attributes.mid===e)))||void 0===r?void 0:r.attributes.ssrcs;return null==i?void 0:i[0].ssrcId}}async setRemoteDescription(e){var t;await this.peerConnection.setRemoteDescription(e),bn(t=[\"connected\",\"completed\"]).call(t,this.peerConnection.iceConnectionState)||(this.isReady=!0,this.addRemoteCandidate())}mungReceiveAnswerSDP(e,t,i){const n=JU.parse(e),r=n.mediaDescriptions.find((e=>e.attributes.mid===t));return r&&(i===av.AUDIO&&\"audio\"===r.media.mediaType&&Lx(r),this.useXR&&kx(n)),JU.print(n)}};function jx(e,t,i){const n=e[t];if(\"function\"!=typeof n)throw new Error(\"Cannot use mutex on object property.\");return i.value=async function(){const e=this.mutex,i=await e.lock(\"From P2PConnection.\".concat(t));try{for(var r=arguments.length,s=new Array(r),o=0;o{if(!i)return n.stopCapture&&n.stopCapture();if(i.paused&&i.play(),i.videoHeight>2&&i.videoWidth>2){const e=i.videoWidth,t=i.videoHeight/e,r=n.width*t;Math.abs(r-n.height)>=2&&(jC.debug(\"adjust low stream resolution\",\"\".concat(n.width,\"x\").concat(n.height,\" -> \").concat(n.width,\"x\").concat(r)),n.height=r)}o.drawImage(i,0,0,n.width,n.height),c.requestFrame&&c.requestFrame(),s!==e._mediaStreamTrack&&(s=e._mediaStreamTrack,i.srcObject=new MediaStream([s]))},n.stopCapture=Tb((()=>n.startCapture&&n.startCapture()),r);const d=c.stop;return c.stop=()=>{d.call(c),i&&(i.remove(),i.srcObject=null,i=null),n&&(n.width=0,n.remove(),n.stopCapture&&n.stopCapture(),n.startCapture=void 0,n.stopCapture=void 0,n=null),jC.debug(\"clean low stream renderer\")},c}var Wx,Hx,Kx,Yx,qx,zx,Jx,Xx,Qx,Zx,$x;DI([jx,PI(\"design:type\",Function),PI(\"design:paramtypes\",[Object]),PI(\"design:returntype\",cg)],Bx.prototype,\"establish\",null),DI([jx,PI(\"design:type\",Function),PI(\"design:paramtypes\",[Object]),PI(\"design:returntype\",cg)],Bx.prototype,\"connect\",null),DI([jx,PI(\"design:type\",Function),PI(\"design:paramtypes\",[String,Array,String,String]),PI(\"design:returntype\",cg)],Bx.prototype,\"receive\",null),DI([jx,PI(\"design:type\",Function),PI(\"design:paramtypes\",[String,Array,String,String]),PI(\"design:returntype\",cg)],Bx.prototype,\"mockReceive\",null),DI([jx,PI(\"design:type\",Function),PI(\"design:paramtypes\",[Array]),PI(\"design:returntype\",cg)],Bx.prototype,\"stopReceiving\",null),DI([jx,PI(\"design:type\",Function),PI(\"design:paramtypes\",[Object]),PI(\"design:returntype\",cg)],Bx.prototype,\"restartICE\",null),DI([jx,PI(\"design:type\",Function),PI(\"design:paramtypes\",[]),PI(\"design:returntype\",void 0)],Bx.prototype,\"close\",null),DI([jx,PI(\"design:type\",Function),PI(\"design:paramtypes\",[String,lb]),PI(\"design:returntype\",cg)],Bx.prototype,\"updateEncoderConfig\",null),DI([jx,PI(\"design:type\",Function),PI(\"design:paramtypes\",[String,lb]),PI(\"design:returntype\",cg)],Bx.prototype,\"updateSendParameters\",null),DI([jx,PI(\"design:type\",Function),PI(\"design:paramtypes\",[lb,String]),PI(\"design:returntype\",cg)],Bx.prototype,\"replaceTrack\",null),DI([jx,PI(\"design:type\",Function),PI(\"design:paramtypes\",[Array]),PI(\"design:returntype\",cg)],Bx.prototype,\"muteLocal\",null),DI([jx,PI(\"design:type\",Function),PI(\"design:paramtypes\",[Array]),PI(\"design:returntype\",cg)],Bx.prototype,\"unmuteLocal\",null),function(e){e[e.HEIGHT=2033]=\"HEIGHT\",e[e.FRAME_RATE=2034]=\"FRAME_RATE\",e[e.WIDTH=2035]=\"WIDTH\"}(Wx||(Wx={})),function(e){e[e.HEIGHT=2072]=\"HEIGHT\",e[e.FRAME_RATE=2074]=\"FRAME_RATE\",e[e.WIDTH=2076]=\"WIDTH\"}(Hx||(Hx={})),function(e){e[e.FRAME_RATE=2002]=\"FRAME_RATE\",e[e.WIDTH=2003]=\"WIDTH\",e[e.HEIGHT=2004]=\"HEIGHT\",e[e.PACKAGE_LOST=2005]=\"PACKAGE_LOST\",e[e.AVG_ENCODE=2007]=\"AVG_ENCODE\",e[e.NACKS=2009]=\"NACKS\",e[e.PLIS=2010]=\"PLIS\",e[e.FIRS=2011]=\"FIRS\",e[e.BITRATE=2012]=\"BITRATE\",e[e.PACKAGE_RATE=2031]=\"PACKAGE_RATE\",e[e.ADAPTATION=2032]=\"ADAPTATION\",e[e.ACTUAL_ENCODED=2060]=\"ACTUAL_ENCODED\",e[e.BANDWIDTH=2061]=\"BANDWIDTH\",e[e.RETRANSMIT=2062]=\"RETRANSMIT\",e[e.TARGET_ENCODED=2064]=\"TARGET_ENCODED\",e[e.TRANSMIT=2066]=\"TRANSMIT\",e[e.FREEZE=2082]=\"FREEZE\",e[e.DISABLED=2095]=\"DISABLED\",e[e.PLAYER_STATUS=2128]=\"PLAYER_STATUS\",e[e.QP_SUM=2143]=\"QP_SUM\"}(Kx||(Kx={})),function(e){e[e.BITRATE=2069]=\"BITRATE\",e[e.PACKAGE_LOST=2070]=\"PACKAGE_LOST\",e[e.PACKAGE_RATE=2071]=\"PACKAGE_RATE\",e[e.HEIGHT=2073]=\"HEIGHT\",e[e.FRAME_RATE=2075]=\"FRAME_RATE\",e[e.WIDTH=2077]=\"WIDTH\"}(Yx||(Yx={})),function(e){e[e.JITTER=-1]=\"JITTER\",e[e.PACKAGE_LOST=2014]=\"PACKAGE_LOST\",e[e.WIDTH=2018]=\"WIDTH\",e[e.HEIGHT=2019]=\"HEIGHT\",e[e.FRAME_RATE=2020]=\"FRAME_RATE\",e[e.JITTER_BUFFER=2023]=\"JITTER_BUFFER\",e[e.CURRENT_DELAY=2024]=\"CURRENT_DELAY\",e[e.NACKS=2026]=\"NACKS\",e[e.PLIS=2027]=\"PLIS\",e[e.FIRS=2028]=\"FIRS\",e[e.BITRATE=2029]=\"BITRATE\",e[e.PACKAGE_RATE=2078]=\"PACKAGE_RATE\",e[e.FREEZE=2084]=\"FREEZE\",e[e.DISABLED=2101]=\"DISABLED\",e[e.PLAYER_STATUS=2129]=\"PLAYER_STATUS\",e[e.QP_SUM=2144]=\"QP_SUM\",e[e.I_FRAME_DELAY=2149]=\"I_FRAME_DELAY\"}(qx||(qx={})),function(e){e[e.FRAME_RATE_DECODE=2021]=\"FRAME_RATE_DECODE\",e[e.FRAME_RATE_RENDER=2022]=\"FRAME_RATE_RENDER\",e[e.FREEZE_TIME=2109]=\"FREEZE_TIME\",e[e.FREEZE_TIME_RENDER=2147]=\"FREEZE_TIME_RENDER\"}(zx||(zx={})),function(e){e[e.PCM_LEVEL=2104]=\"PCM_LEVEL\"}(Jx||(Jx={})),function(e){e[e.PACKAGE_LOST=-1]=\"PACKAGE_LOST\",e[e.LEVEL=2038]=\"LEVEL\",e[e.BITRATE=2039]=\"BITRATE\",e[e.PACKAGE_RATE=2040]=\"PACKAGE_RATE\",e[e.AEC_RETURN_LOSS=2041]=\"AEC_RETURN_LOSS\",e[e.AEC_RETURN_LOSS_ENH=2042]=\"AEC_RETURN_LOSS_ENH\",e[e.FREEZE=2081]=\"FREEZE\",e[e.DISABLED=2096]=\"DISABLED\"}(Xx||(Xx={})),function(e){e[e.BITRATE=2044]=\"BITRATE\",e[e.PACKAGE_LOST=2045]=\"PACKAGE_LOST\",e[e.PACKAGE_RATE=2046]=\"PACKAGE_RATE\",e[e.CURRENT_DELAY=2047]=\"CURRENT_DELAY\",e[e.JITTER_BUFFER=2054]=\"JITTER_BUFFER\",e[e.JITTER=2055]=\"JITTER\",e[e.FREEZE=2083]=\"FREEZE\",e[e.DISABLED=2102]=\"DISABLED\",e[e.PCM_LEVEL=2105]=\"PCM_LEVEL\",e[e.PLAYER_STATUS=2130]=\"PLAYER_STATUS\",e[e.CONCEALED_SAMPLES=2148]=\"CONCEALED_SAMPLES\"}(Qx||(Qx={})),function(e){e[e.FREEZE_TIME=-1]=\"FREEZE_TIME\",e[e.LEVEL=2043]=\"LEVEL\"}(Zx||(Zx={})),function(e){e[e.RTT=2006]=\"RTT\",e[e.CONN_TYPE=801]=\"CONN_TYPE\"}($x||($x={}));const eV=1e3,tV=3;function iV(e,t,i){null!=i&&Number.isFinite(i)&&(e[t]=Math.round(Math.max(0,i)))}function nV(e){const t={[$x.CONN_TYPE]:0,[$x.RTT]:e.rtt};switch(e.selectedCandidatePair.localCandidate.candidateType){case\"relay\":{const i=e.selectedCandidatePair.localCandidate.relayProtocol;\"udp\"===i&&(t[$x.CONN_TYPE]=1),\"tcp\"===i&&(t[$x.CONN_TYPE]=3),\"tls\"===i&&(t[$x.CONN_TYPE]=4);break}case\"srflx\":t[$x.CONN_TYPE]=2}return t}class rV extends dT{constructor(e){super(),sh(this,\"store\",void 0),sh(this,\"uploadWRTCStatsTimer\",void 0),sh(this,\"uploadOutboundDenoiserStatsTimer\",void 0),sh(this,\"uploadExtStatsTimer\",void 0),sh(this,\"uploadExtUsageStatsTimer\",void 0),sh(this,\"uploadInboundExtStatsTimer\",void 0),sh(this,\"requestStats\",void 0),sh(this,\"requestTransportStats\",void 0),sh(this,\"requestLocalMedia\",void 0),sh(this,\"requestRemoteMedia\",void 0),sh(this,\"requestAllTracks\",void 0),sh(this,\"requestVideoIsReady\",void 0),sh(this,\"requestUploadStats\",void 0),sh(this,\"requestUpload\",void 0),sh(this,\"uploadOutboundStarted\",!1),sh(this,\"uploadInboundStarted\",!1),sh(this,\"uploadTransportStarted\",!1),sh(this,\"uploadExtensionUsageStarted\",!1),sh(this,\"lastRecvStats\",void 0),sh(this,\"lastSendStats\",void 0),sh(this,\"lastFullRecvStats\",void 0),sh(this,\"lastFullSendStats\",void 0),sh(this,\"needUploadRenderFreezeTime\",!0),this.store=e}uploadWRTCStats(e){if(!this.requestStats||!this.requestUploadStats)return;let t,i;if(this.uploadTransportStarted&&(t=this.requestStats(),this.store.useP2P&&(i=this.requestStats(!0))),!t&&this.uploadOutboundStarted&&(t=this.requestStats()),!i&&this.uploadInboundStarted&&(i=this.requestStats(!0)),t||i){const n={};if(this.uploadTransportStarted&&t){const r=this.getTransportStats(t,i,e);r&&(n.misc=[r])}if(this.uploadOutboundStarted&&t){const i=this.getOutboundStats(t,e?this.lastSendStats:this.lastFullSendStats,e);i&&(n.outbound=[i])}if(this.uploadInboundStarted&&i){const t=this.getInboundStats(i,e?this.lastRecvStats:this.lastFullRecvStats,e);t&&(n.inbound=t)}this.requestUploadStats(n)}this.lastRecvStats=i,this.lastSendStats=t,e||(this.lastFullRecvStats=i,this.lastFullSendStats=t)}startUploadWRTCStats(){if(this.uploadWRTCStatsTimer)return;let e=1;this.uploadWRTCStatsTimer=window.setInterval((()=>{if(!this.uploadTransportStarted&&!this.uploadInboundStarted&&!this.uploadOutboundStarted)return this.stopUploadWRTCStats();this.uploadWRTCStats(e!==tV),++e===tV+1&&(e=1)}),eV)}stopUploadWRTCStats(){window.clearInterval(this.uploadWRTCStatsTimer),this.uploadWRTCStatsTimer=void 0,this.lastSendStats&&(this.lastSendStats.videoSend=[],this.lastSendStats.audioSend=[],this.lastSendStats=void 0),this.lastRecvStats&&(this.lastRecvStats.videoRecv=[],this.lastRecvStats.audioRecv=[],this.lastRecvStats=void 0)}getTransportStats(e,t,i){if(!this.requestStats)return;if(i)return null==e.rtt?void 0:{addition:{[$x.RTT]:e.rtt,[$x.CONN_TYPE]:void 0}};const n=nV(e);if(this.store.useP2P){if(t){const e=nV(t);n[$x.CONN_TYPE]+=e[$x.CONN_TYPE]<<3}n[$x.CONN_TYPE]+=110}else n[$x.CONN_TYPE]+=100;return{addition:n}}getOutboundStats(e,t,i){if(!this.requestUploadStats||!this.requestLocalMedia)return;const n=this.requestLocalMedia();if(!n||0===n.length)return;let r,s,o;return n.forEach((n=>{let[a,{track:c,ssrcs:d}]=n;switch(a){case lv.LocalVideoLowTrack:case lv.LocalVideoTrack:if(a===lv.LocalVideoTrack){const n=function(e,t,i,n,r){const s=t.videoSend.find((t=>t.ssrc===e));if(!s)return;const o={},{sentFrame:a,inputFrame:c}=s;if(c&&a){const e=c.frameRate,t=a.frameRate;o[Kx.FREEZE]=function(e,t){let i=!0;return i=!(e<=5)&&(e<=10?t<3:e<=20?t<4:t<5),i}(e,t)?1:0}if(iV(o,Kx.QP_SUM,s.qpSumPerFrame),r)return o;switch(a&&(iV(o,Kx.HEIGHT,a.height),iV(o,Kx.WIDTH,a.width),iV(o,Kx.FRAME_RATE,a.frameRate)),o[Kx.DISABLED]=n._originMediaStreamTrack&&!n._originMediaStreamTrack.enabled||n._mediaStreamTrack&&!n._mediaStreamTrack.enabled?1:0,s.adaptionChangeReason){case\"none\":o[Kx.ADAPTATION]=0;break;case\"cpu\":o[Kx.ADAPTATION]=1;break;case\"bandwidth\":o[Kx.ADAPTATION]=2;break;case\"other\":o[Kx.ADAPTATION]=3}o[Kx.PLAYER_STATUS]=ab[n._player?n._player.videoElementStatus:\"uninit\"],iV(o,Kx.NACKS,s.nacksCount),iV(o,Kx.PLIS,s.plisCount),iV(o,Kx.FIRS,s.firsCount),iV(o,Kx.AVG_ENCODE,s.avgEncodeMs);const d=i&&i.videoSend.find((t=>t.ssrc===e));if(d){let e=r?eV:eV*tV;d.timestamp&&s.timestamp&&(e=s.timestamp-d.timestamp),null!=d.packets&&null!=s.packets&&iV(o,Kx.PACKAGE_RATE,1e3*(s.packets-d.packets)/e),null!=s.packetsLost&&null!=d.packetsLost&&iV(o,Kx.PACKAGE_LOST,s.packetsLost-d.packetsLost),null!=d.bytes&&null!=s.bytes&&iV(o,Kx.BITRATE,8*(s.bytes-d.bytes)/e)}return o}(d[0].ssrcId,e,t,c,i),r=i?null:function(e,t,i){const n=t.videoSend.find((t=>t.ssrc===e));if(!n)return null;const r={},s=n.inputFrame,o=s&&s.height||i&&i._videoHeight||0,a=s&&s.width||i&&i._videoWidth||0,c=s&&s.frameRate||0;return iV(r,Wx.HEIGHT,o),iV(r,Wx.WIDTH,a),iV(r,Wx.FRAME_RATE,c),r}(d[0].ssrcId,e,c),o=i?null:function(e){const t={};return iV(t,Kx.RETRANSMIT,e.bitrate.retransmit),iV(t,Kx.TARGET_ENCODED,e.bitrate.targetEncoded),iV(t,Kx.ACTUAL_ENCODED,e.bitrate.actualEncoded),iV(t,Kx.TRANSMIT,e.bitrate.transmit),iV(t,Kx.BANDWIDTH,e.sendBandwidth),t}(e);s=Object.assign({},n,r,o)}else o=i?void 0:function(e,t,i){const n=t.videoSend.find((t=>t.ssrc===e));if(!n)return;const r={},s=n.sentFrame;if(s&&(iV(r,Yx.HEIGHT,s.height),iV(r,Yx.WIDTH,s.width),iV(r,Yx.FRAME_RATE,s.frameRate)),i){const t=i.videoSend.find((t=>t.ssrc===e));if(t){let e=eV*tV;t.timestamp&&n.timestamp&&(e=n.timestamp-t.timestamp),null!=t.packets&&null!=n.packets&&iV(r,Yx.PACKAGE_RATE,1e3*(n.packets-t.packets)/e),null!=n.packetsLost&&null!=t.packetsLost&&iV(r,Yx.PACKAGE_LOST,n.packetsLost-t.packetsLost),null!=t.bytes&&null!=n.bytes&&iV(r,Yx.BITRATE,8*(n.bytes-t.bytes)/e)}}return r}(d[0].ssrcId,e,t);break;case lv.LocalAudioTrack:r=i?void 0:function(e,t,i,n){const r=t.audioSend.find((t=>t.ssrc===e));if(!r)return;const s={};s[Xx.DISABLED]=n._originMediaStreamTrack&&!n._originMediaStreamTrack.enabled||n._mediaStreamTrack&&!n._mediaStreamTrack.enabled?1:0;const o=n._source.getAccurateVolumeLevel(),a=r.inputLevel;iV(s,Xx.LEVEL,100*(null==a?o:a)),iV(s,Jx.PCM_LEVEL,100*o),iV(s,Xx.AEC_RETURN_LOSS,r.aecReturnLoss),iV(s,Xx.AEC_RETURN_LOSS_ENH,r.aecReturnLossEnhancement),s[Xx.FREEZE]=0;const c=i&&i.audioSend.find((t=>t.ssrc===e));if(c){let e=eV*tV;c.timestamp&&r.timestamp&&(e=r.timestamp-c.timestamp),null!=c.bytes&&null!=r.bytes&&iV(s,Xx.BITRATE,8*(r.bytes-c.bytes)/e),null!=c.packets&&null!=r.packets&&iV(s,Xx.PACKAGE_RATE,1e3*(r.packets-c.packets)/e)}return s}(d[0].ssrcId,e,t,c)}})),{high:s,low:o,audio:r}}getInboundStats(e,t,i){if(!this.requestRemoteMedia)return;const n=this.requestRemoteMedia()||[],r=[];return n.forEach((n=>{let[s,o]=n;const a={peer:s.uid};if(o.has(av.VIDEO)&&s.videoTrack){const n=s._videoSSRC&&this.requestVideoIsReady&&this.requestVideoIsReady(s._videoSSRC)||!1,r=s.videoTrack?function(e,t,i,n,r,s,o){const a=t.videoRecv.find((t=>t.ssrc===e));if(!a)return;const c={},{receivedFrame:d,outputFrame:l,decodeFrameRate:u}=a,h=i&&i.videoRecv.find((t=>t.ssrc===e));if(c[qx.FREEZE]=r&&mV.isRemoteVideoFreeze(n,a,h)?1:0,iV(c,zx.FRAME_RATE_DECODE,u),iV(c,qx.QP_SUM,a.qpSumPerFrame),a.framesRateFirefox&&iV(c,qx.FRAME_RATE,a.framesRateFirefox),d&&iV(c,qx.FRAME_RATE,d.frameRate),h){const e=t.timestamp-i.timestamp||(o?eV:tV*eV);null!=a.packetsLost&&null!=h.packetsLost&&iV(c,qx.PACKAGE_LOST,a.packetsLost-h.packetsLost),null!=h.bytes&&null!=a.bytes&&iV(c,qx.BITRATE,8*(a.bytes-h.bytes)/e),null!=h.packets&&null!=a.packets&&iV(c,qx.PACKAGE_RATE,1e3*(a.packets-h.packets)/e)}if(o)return c;if(d?(iV(c,qx.HEIGHT,d.height),iV(c,qx.WIDTH,d.width)):n&&(iV(c,qx.HEIGHT,n._videoHeight||0),iV(c,qx.WIDTH,n._videoWidth||0)),l&&iV(c,zx.FRAME_RATE_RENDER,l.frameRate),iV(c,qx.JITTER_BUFFER,a.jitterBufferMs),iV(c,qx.CURRENT_DELAY,a.currentDelayMs),iV(c,qx.FIRS,a.firsCount),iV(c,qx.NACKS,a.nacksCount),iV(c,qx.PLIS,a.plisCount),n){c[qx.DISABLED]=n._originMediaStreamTrack.enabled&&n._mediaStreamTrack.enabled?0:1;const e=n._player;if(e){const{freezeTimeCounterList:t,renderFreezeAccTime:i}=e;if(t&&t.length>0&&iV(c,zx.FREEZE_TIME,t.splice(0,1)[0]),s&&\"visible\"===Dw.visibility){const t=Math.min(6e3,i);e.renderFreezeAccTime=Math.max(0,i-t),iV(c,zx.FREEZE_TIME_RENDER,t)}}}if(c[qx.PLAYER_STATUS]=ab[n._player?n._player.videoElementStatus:\"uninit\"],h&&void 0!==a.totalInterFrameDelay&&void 0!==a.totalSquaredInterFrameDelay&&void 0!==h.totalInterFrameDelay&&void 0!==h.totalSquaredInterFrameDelay){const e=a.totalInterFrameDelay-h.totalInterFrameDelay,t=a.totalSquaredInterFrameDelay-h.totalSquaredInterFrameDelay,i=a.framesDecodeCount-h.framesDecodeCount,n=e/i*1e3,r=Math.round(1e3*Math.sqrt((t-Math.pow(e,2)/i)/i));!isNaN(r)&&n+r>Math.max(3*n,n+150)&&(c[qx.I_FRAME_DELAY]=r)}return c}(s._videoSSRC,e,t,s.videoTrack,!0===n,this.needUploadRenderFreezeTime,i):void 0;r&&(a.video=r)}if(o.has(av.AUDIO)&&s.audioTrack){const n=s.audioTrack?function(e,t,i,n,r){const s=t.audioRecv.find((t=>t.ssrc===e));if(!s)return;const o={},a=i&&i.audioRecv.find((t=>t.ssrc===e)),{receivedFrames:c,droppedFrames:d}=s;var l,u;if(iV(o,Qx.JITTER,s.jitterMs),null!=c&&null!=d&&(o[Qx.FREEZE]=(u=d,0===(l=c)||100*u/l>20?1:0)),a){const e=t.timestamp-i.timestamp||(r?eV:eV*tV);null!=s.packets&&null!=a.packets&&iV(o,Qx.PACKAGE_RATE,1e3*(s.packets-a.packets)/e),null!=a.bytes&&null!=s.bytes&&iV(o,Qx.BITRATE,8*(s.bytes-a.bytes)/e),null!=s.packetsLost&&null!=a.packetsLost&&iV(o,Qx.PACKAGE_LOST,s.packetsLost-a.packetsLost)}if(r)return o;const h=n._source.getAccurateVolumeLevel(),p=s.outputLevel;if(iV(o,Zx.LEVEL,100*(null==p?h:p)),iV(o,Qx.PCM_LEVEL,100*h),n&&(o[Qx.DISABLED]=n._originMediaStreamTrack.enabled&&n._mediaStreamTrack.enabled?0:1),iV(o,Qx.JITTER_BUFFER,s.jitterBufferMs),iV(o,Qx.CURRENT_DELAY,s.jitterBufferMs),o[Qx.PLAYER_STATUS]=ab[Gb.getPlayerState(n.getTrackId())],a){const e=s.concealedSamples-a.concealedSamples;e>0&&iV(o,Qx.CONCEALED_SAMPLES,e)}return o}(s._audioSSRC,e,t,s.audioTrack,i):void 0;n&&(a.audio=n)}(a.video||a.audio)&&r.push(a)})),this.needUploadRenderFreezeTime=!this.needUploadRenderFreezeTime,r}startUploadTransportStats(){this.uploadTransportStarted=!0,this.uploadWRTCStatsTimer||this.startUploadWRTCStats()}stopUploadTransportStats(){this.uploadTransportStarted=!1}startUploadOutboundStats(){this.uploadOutboundStarted||(this.uploadOutboundStarted=!0,this.uploadWRTCStatsTimer||this.startUploadWRTCStats(),this.uploadOutboundDenoiserStatsTimer&&window.clearInterval(this.uploadOutboundDenoiserStatsTimer),this.uploadOutboundDenoiserStatsTimer=window.setInterval((()=>{if(!this.requestAllTracks||!this.requestUpload)return;const e=(this.requestAllTracks()||[]).find((e=>e instanceof tw));if(e&&e._external.getDenoiserStats){const t=e._external.getDenoiserStats();t&&this.requestUpload(mI.DENOISER_STATS,t)}}),2e3),this.uploadExtStatsTimer&&window.clearInterval(this.uploadExtStatsTimer),this.uploadExtStatsTimer=window.setInterval((()=>{if(!this.requestAllTracks||!this.requestUpload)return;this.requestAllTracks().forEach((e=>{e.getProcessorStats().forEach((e=>{this.requestUpload&&this.requestUpload(e.type,e.stats)}))}))}),2e3))}stopUploadOutboundStats(){this.uploadOutboundStarted&&(this.uploadOutboundStarted=!1,this.lastSendStats&&(this.lastSendStats.videoSend=[],this.lastSendStats.audioSend=[],this.lastSendStats=void 0),this.uploadOutboundDenoiserStatsTimer&&window.clearInterval(this.uploadOutboundDenoiserStatsTimer),this.uploadOutboundDenoiserStatsTimer=void 0)}startUploadInboundStats(){this.uploadInboundStarted||(this.uploadInboundStarted=!0,this.uploadWRTCStatsTimer||this.startUploadWRTCStats(),this.uploadInboundExtStatsTimer&&window.clearInterval(this.uploadInboundExtStatsTimer),this.uploadInboundExtStatsTimer=window.setInterval((()=>{if(!this.requestUpload||!this.requestRemoteMedia)return;(this.requestRemoteMedia()||[]).forEach((e=>{let[t,i]=e;if(i.has(av.VIDEO)&&t.videoTrack){t.videoTrack.getProcessorStats().forEach((e=>{this.requestUpload&&this.requestUpload(e.type,e.stats)}))}if(i.has(av.AUDIO)&&t.audioTrack){t.audioTrack.getProcessorStats().forEach((e=>{this.requestUpload&&this.requestUpload(e.type,e.stats)}))}}))}),2e3))}stopUploadInboundStats(){this.uploadInboundStarted&&(this.uploadInboundStarted=!1,this.lastRecvStats&&(this.lastRecvStats.videoRecv=[],this.lastRecvStats.audioRecv=[],this.lastRecvStats=void 0))}startUploadExtensionUsageStats(){if(this.uploadExtensionUsageStarted)return;this.uploadExtensionUsageStarted=!0,this.uploadExtUsageStatsTimer&&window.clearInterval(this.uploadExtUsageStatsTimer);const e=new Map;this.uploadExtUsageStatsTimer=window.setInterval((async()=>{const t=Date.now(),i={connectionInterval:RC(\"EXTENSION_USAGE_UPLOAD_INTERVAL\")/1e3,details:[],lts:t};let n=[];const r=this.requestAllTracks&&this.requestAllTracks()||[];for(const e of r)!e.muted&&e.enabled&&(n=n.concat(await e.getProcessorUsage()));const s=this.requestRemoteMedia&&this.requestRemoteMedia()||[];for(const[e,t]of s)t.has(av.VIDEO)&&e.videoTrack&&(n=n.concat(await e.videoTrack.getProcessorUsage())),t.has(av.AUDIO)&&e.audioTrack&&(n=n.concat(await e.audioTrack.getProcessorUsage()));if(0===n.length)return;i.details=function(e,t){const i={};for(const{id:o,value:a,level:c,direction:d}of e){var n;const e=null!==(n=t.get(o))&&void 0!==n?n:0,l=2===a?e+RC(\"EXTENSION_USAGE_UPLOAD_INTERVAL\")/1e3:e;var r,s;t.set(o,l),i[o]?(2===a&&(i[o].value=a),c>i[o].level&&(i[o].level=c),\"remote\"===d&&(i[o].remoteUidCount+=1),i[o].totalTs=null!==(r=t.get(o))&&void 0!==r?r:0):i[o]={value:a,level:c,remoteUidCount:\"local\"===d?0:1,totalTs:null!==(s=t.get(o))&&void 0!==s?s:0}}return Object.keys(i).map((e=>{const{level:t,value:n,totalTs:r}=i[e];return{id:e,level:t,value:n,totalTs:r}}))}(n,e);const o=Date.now(),a=o>t?o:t+1;this.requestUpload&&this.requestUpload(mI.EXTENSION_USAGE_STATS,{usageStats:i,sendTs:a})}),RC(\"EXTENSION_USAGE_UPLOAD_INTERVAL\"))}stopUploadExtensionUsageStats(){this.uploadExtensionUsageStarted&&(this.uploadExtensionUsageStarted=!1,this.uploadExtUsageStatsTimer&&window.clearInterval(this.uploadExtUsageStatsTimer),this.uploadExtUsageStatsTimer=void 0)}}class sV{get hasVideo(){return this._video_enabled_&&!this._video_muted_&&this._video_added_}get hasAudio(){return this._audio_enabled_&&!this._audio_muted_&&this._audio_added_}get audioTrack(){if(this.hasAudio||this._audio_pre_subscribed)return this._audioTrack}get videoTrack(){if(this.hasVideo||this._video_pre_subscribed)return this._videoTrack}get dataChannels(){return this._dataChannels}constructor(e,t){sh(this,\"uid\",void 0),sh(this,\"_uintid\",void 0),sh(this,\"_trust_in_room_\",!0),sh(this,\"_trust_audio_enabled_state_\",!0),sh(this,\"_trust_video_enabled_state_\",!0),sh(this,\"_trust_audio_mute_state_\",!0),sh(this,\"_trust_video_mute_state_\",!0),sh(this,\"_audio_muted_\",!1),sh(this,\"_video_muted_\",!1),sh(this,\"_audio_enabled_\",!0),sh(this,\"_video_enabled_\",!0),sh(this,\"_audio_added_\",!1),sh(this,\"_video_added_\",!1),sh(this,\"_is_pre_created\",!1),sh(this,\"_video_pre_subscribed\",!1),sh(this,\"_audio_pre_subscribed\",!1),sh(this,\"_trust_video_stream_added_state_\",!0),sh(this,\"_trust_audio_stream_added_state_\",!0),sh(this,\"_audioTrack\",void 0),sh(this,\"_videoTrack\",void 0),sh(this,\"_dataChannels\",[]),sh(this,\"_audioSSRC\",void 0),sh(this,\"_videoSSRC\",void 0),sh(this,\"_audioOrtc\",void 0),sh(this,\"_videoOrtc\",void 0),sh(this,\"_cname\",void 0),sh(this,\"_rtxSsrcId\",void 0),sh(this,\"_videoMid\",void 0),sh(this,\"_audioMid\",void 0),this.uid=e,this._uintid=t}}var oV;function aV(e,t){var i;let n;switch(t){case lv.LocalAudioTrack:n=JI.Audio;break;case lv.LocalVideoTrack:n=bn(i=e._hints).call(i,jA.SCREEN_TRACK)?JI.Screen:JI.High;break;case lv.LocalVideoLowTrack:n=JI.Low}return n}function cV(e){const t=IA();if(e.some((e=>e._bypassWebAudio)))throw new Kg(Hg.NOT_SUPPORTED,\"cannot publish multiple tracks which one of them configured with bypassWebAudio\");if(!t.webAudioMediaStreamDest)throw new Kg(Hg.NOT_SUPPORTED,\"cannot publish multiple tracks because your browser does not support audio mixing\")}function dV(e,t){cV(e);const i=t||new nw;return e.forEach((e=>i.addAudioTrack(e))),i}function lV(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function uV(e){for(var t=1;t{const n=await this.sendMutex.lock(\"Locking from P2PChannel2.handleMuteLocalTrack\");try{if(!this.sendConnection||this.state!==uv.Connected)return void i(new Kg(Hg.INVALID_OPERATION,\"Cannot call P2PChannel2.handleMuteLocalTrack before sendConnection established.\"));const o=this.filterTobeMutedTracks(e);if(0===o.length)return void t();const a=o.find((e=>\"videoLowTrack\"===e[0]));if(a){a[1].track._originMediaStreamTrack.stop()}await this.sendConnection.muteLocal(o.map((e=>{let[,{id:t}]=e;return t})));let c=!1;var r,s;if(\"video\"===e.trackMediaType)c=!(null===(r=this.localTrackMap.get(lv.LocalAudioTrack))||void 0===r||!r.track._muted);else c=void 0===(null===(s=this.localTrackMap.get(lv.LocalVideoTrack))||void 0===s?void 0:s.id);const d=this.createMuteMessage(o);await yT(this,hv.RequestMuteLocal,d);const l=\"video\"===e.trackMediaType?Av.MUTE_LOCAL_VIDEO:Av.MUTE_LOCAL_AUDIO;await yT(this,hv.RequestP2PMuteLocal,{action:l,message:d,isMuteAll:c}),t()}catch(e){i(e)}finally{n()}})),sh(this,\"handleUnmuteLocalTrack\",(async(e,t,i)=>{const n=await this.sendMutex.lock(\"Locking from P2PChannel2.handleUnmuteLocalTrack\");try{if(!this.sendConnection||this.state!==uv.Connected)return void i(new Kg(Hg.INVALID_OPERATION,\"Cannot call P2PChannel2.handleUnmuteLocalTrack before sendConnection established.\"));const r=this.filterTobeUnmutedTracks(e);if(0===r.length)return void t();await this.sendConnection.unmuteLocal(r.map((e=>{let[,{id:t}]=e;return t})));const s=this.createUnmuteMessage(r),o=\"video\"===e.trackMediaType?Av.UNMUTE_LOCAL_VIDEO:Av.UNMUTE_LOCAL_AUDIO;await yT(this,hv.RequestP2PMuteLocal,{action:o,message:s}),t()}catch(e){i(e)}finally{n()}})),sh(this,\"handleUpdateVideoEncoder\",(async(e,t,i)=>{const n=await this.sendMutex.lock(\"Locking from P2PChannel2.handleSetVideoEncoder\");try{const i=this.localTrackMap.get(lv.LocalVideoTrack);if(!this.sendConnection||!i||i.track!==e||this.state!==uv.Connected)return void t();const{id:r,track:s}=i;r&&(await this.sendConnection.updateSendParameters(r,s),await this.sendConnection.updateEncoderConfig(r,s),this.emit(hv.UpdateVideoEncoder,s)),t()}catch(e){i(e)}finally{n()}})),sh(this,\"handleSetOptimizationMode\",(async(e,t,i)=>{const n=await this.sendMutex.lock(\"Locking from P2PChannel2.handleSetOptimizationMode\");try{const i=this.localTrackMap.get(lv.LocalVideoTrack);if(!this.sendConnection||!i||i.track!==e||this.state!==uv.Connected)return;const{id:r,track:s}=i;r&&await this.sendConnection.updateSendParameters(r,s),t()}catch(e){i(e)}finally{n()}})),sh(this,\"handleReplaceTrack\",(async(e,t,i,n)=>{let r;jC.debug(\"[\".concat(this.store.clientId,\"] P2PChannel2 handleReplaceTrack for [track-id-\").concat(e.getTrackId(),\"]\")),\"boolean\"==typeof n&&n||(r=await this.sendMutex.lock(\"From P2PChannel2.handleReplaceTrack\"));try{var s;const i=Array.from(this.localTrackMap.entries()).find((t=>{let[,{track:i}]=t;return e===i}));if(!this.sendConnection||!i||void 0===i[1].id||this.state!==uv.Connected)return void t();if(await(null===(s=this.sendConnection)||void 0===s?void 0:s.replaceTrack(e,i[1].id)),i[0]===lv.LocalVideoTrack&&IA().supportDualStreamEncoding){const t=this.localTrackMap.get(lv.LocalVideoLowTrack);if(t){const i=e._mediaStreamTrack.clone();t.track._originMediaStreamTrack.stop(),t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i,await new cg(((e,i)=>{this.handleReplaceTrack(t.track,e,i,!0)}))}}t()}catch(e){i(e)}finally{var o;null===(o=r)||void 0===o||o()}})),sh(this,\"handleGetLocalVideoStats\",(e=>{e(this.statsCollector.getLocalVideoTrackStats())})),sh(this,\"handleGetLocalAudioStats\",(e=>{e(this.statsCollector.getLocalAudioTrackStats())})),sh(this,\"handleGetRemoteVideoStats\",(e=>this.statsCollector.getRemoteVideoTrackStats(e.uid)[e.uid])),sh(this,\"handleGetRemoteAudioStats\",(e=>this.statsCollector.getRemoteAudioTrackStats(e.uid)[e.uid])),this.store=e,this.statsCollector=t,this.statsCollector.addP2PChannel(this),this.statsUploader=new rV(e),this.bindStatsUploaderEvents(),this.reconnectInterval=window.setInterval((()=>{[this.sendConnection,this.recvConnection].forEach((e=>{e&&(\"disconnected\"!==e.iceConnectionState&&\"failed\"!==e.iceConnectionState||this.handleDisconnect(e.direction))}))}),RC(\"ICE_RESTART_INTERVAL\"))}async startP2PConnection(e,t){throw new Kg(Hg.NOT_SUPPORTED,\"p2p mode does not support startP2PConnection.\")}async connect(e,t,i,n,r,s){throw new Kg(Hg.NOT_SUPPORTED,\"p2p mode does not support connect.\")}async startP2P(e,t){let i;try{if(t){this.recvConnection&&(jC.warning(\"[\".concat(this.store.clientId,\"] P2PChannel.startP2P reset recvConnection.\")),this.recvConnection.close(),this.unbindConnectionEvents(this.recvConnection)),i=await this.recvMutex.lock(\"From P2PChannel.startP2P\"),this.recvConnection=new Bx(e,this.store,TI.RECEIVE_ONLY),this.bindConnectionEvents(this.recvConnection);const n=await this.recvConnection.establish(t);return{iceParameters:n.iceParameters,dtlsParameters:n.dtlsParameters,sdp:n.sdp}}{this.state=uv.New,this.sendConnection&&(jC.warning(\"[\".concat(this.store.clientId,\"] P2PChannel.startP2P reset sendConnection.\")),this.sendConnection.close(),this.unbindConnectionEvents(this.sendConnection)),i=await this.sendMutex.lock(\"From P2PChannel.startP2P\"),this.sendConnection=new Bx(e,this.store),this.store.peerConnectionStart(),this.bindConnectionEvents(this.sendConnection);const t=await this.sendConnection.establish();return{iceParameters:t.iceParameters,dtlsParameters:t.dtlsParameters,sdp:t.sdp}}}finally{i&&i()}}async p2pConnect(e){if(!this.sendConnection)throw new Kg(Hg.UNEXPECTED_ERROR,\"Cannot P2PChannel2.p2pConnect before P2PChannel2.startP2PConnection .\");this.store.peerConnectionStart(),await this.sendConnection.connect(e),this.statsUploader.startUploadTransportStats(),this.statsUploader.startUploadExtensionUsageStats(),this.state=uv.Connected}async addRemoteCandidate(e,t){if(t===TI.RECEIVE_ONLY){if(!this.sendConnection)throw new Kg(Hg.UNEXPECTED_ERROR,\"Cannot P2PChannel2.connect before P2PChannel2.addRemoteCandidate .\");await this.sendConnection.addRemoteCandidate(e)}else{if(!this.recvConnection)throw new Kg(Hg.UNEXPECTED_ERROR,\"Cannot P2PChannel2.connect before P2PChannel2.addRemoteCandidate .\");await this.recvConnection.addRemoteCandidate(e)}}publish(e,t,i){var n=this;return PU((function*(){const r=yield IU(n.sendMutex.lock(\"From P2PChannel.publish\"));try{if(!n.sendConnection||n.state!==uv.Connected){n.throwIfTrackTypeNotMatch(e);const t=e.filter((e=>-1===n.pendingLocalTracks.indexOf(e)));return void(n.pendingLocalTracks=n.pendingLocalTracks.concat(t))}n.store.pubId=n.store.pubId+1,RU.markPublishStart(n.store.clientId,n.store.pubId);const s=n.filterTobePublishedTracks(e,t,i);if(0===s.length)return void(yield IU(n.tryToUnmuteAudio(e)));s.forEach((e=>{let{track:t,type:i}=e;const r=Date.now();n.store.publish(t.getTrackId(),i===lv.LocalAudioTrack?\"audio\":\"video\",r)})),n.bindLocalTrackEvents(s);const o=yield IU(n.sendConnection.send(s.map((e=>{let{track:t}=e;return t})),n.store.codec,n.store.audioCodec)),a=(yield IU(o.next())).value,c=n.createGatewayPublishMessage(s,a);try{yield c}catch(e){throw o.throw(e),(null==e?void 0:e.code)===Hg.WS_ABORT&&s.forEach((e=>{let{track:t}=e;-1===n.pendingLocalTracks.indexOf(t)&&n.pendingLocalTracks.push(t)})),n.unbindLocalTrackEvents(s),e}yield IU(o.next()),s.forEach((e=>{let{type:t}=e;n.statsCollector.addLocalStats(t)})),n.statsUploader.startUploadOutboundStats(),n.assignLocalTracks(s,a),s.forEach((e=>{let{track:t,type:i}=e;const r=Date.now();n.store.publish(t.getTrackId(),i===lv.LocalAudioTrack?\"audio\":\"video\",void 0,r)})),n.startUploadUplinkState()}finally{r()}}))()}async unpublish(e){if(!this.sendConnection||this.state!==uv.Connected)return void(0===e.length?this.pendingLocalTracks.length=0:this.pendingLocalTracks=this.pendingLocalTracks.filter((t=>!bn(e).call(e,t))));const t=this.filterTobeUnpublishedTracks(e);if(0===t.length)return;const i=t.find((e=>\"videoLowTrack\"===e[0]));if(i){i[1].track.close()}const n=this.createGatewayUnpublishMessage(t);if(await this.sendConnection.stopSending(t.map((e=>{let[,{id:t}]=e;return t}))),this.withdrawLocalTracks(t),this.unbindLocalTrackEvents(t.map((e=>{let[t,{track:i}]=e;return{type:t,track:i}}))),t.forEach((e=>{let[t]=e;this.statsCollector.removeLocalStats(t)})),0===this.localTrackMap.size&&(this.statsUploader.stopUploadOutboundStats(),this.stopUploadUplinkState()),this.sendConnection&&this.state===uv.Connected){if(i){i[1].track.close()}return n}e.forEach((e=>{const t=this.pendingLocalTracks.indexOf(e);-1!==t&&this.pendingLocalTracks.splice(t,1)}))}startUploadUplinkState(){if(this.uploadUnplinkStarted)return;this.uploadUnplinkStarted=!0,this.uplinkStateUploadInterval&&window.clearInterval(this.uplinkStateUploadInterval);const e=()=>{const e=[],t=[];Array.from(this.localTrackMap.entries()).forEach((i=>{let[n,{track:r,ssrcs:s}]=i;const o={stream_type:aV(r,n),ssrcs:s};r._muted||!r._enabled?e.push(o):t.push(o)})),e.length>0&&e.forEach((e=>{yT(this,hv.RequestMuteLocal,[e])})),t.length>0&&t.forEach((e=>{yT(this,hv.RequestUnmuteLocal,[e])}))};e(),this.uplinkStateUploadInterval=window.setInterval((()=>{e()}),3e3)}stopUploadUplinkState(){this.uploadUnplinkStarted&&(this.uploadUnplinkStarted=!1,this.uplinkStateUploadInterval&&window.clearInterval(this.uplinkStateUploadInterval))}publishLowStream(e){return PU((function*(){throw new Kg(Hg.NOT_SUPPORTED,\"p2p mode does not support publishLowStream.\")}))()}async republish(){this.pendingLocalTracks.length>0&&(jC.debug(\"[\".concat(this.store.clientId,\"] Emit P2PChannelEvents.RequestRePublish to republish tracks.\")),await vT(this,hv.RequestRePublish,this.pendingLocalTracks),this.emit(hv.MediaReconnectEnd,this.store.uid),this.pendingLocalTracks=[])}async unpublishLowStream(){throw new Kg(Hg.NOT_SUPPORTED,\"p2p mode does not support unpublishLowStream.\")}async subscribe(e,t,i,n){var r;if(!this.recvConnection)throw new Kg(Hg.INVALID_OPERATION,\"Cannot subscribe remote user when recvConnection disconnected.\");if(null!==(r=this.remoteUserMap.get(e))&&void 0!==r&&r.has(t))return;const{track:s,mid:o,transceiver:a}=await this.recvConnection.receive(t,[{ssrcId:i}],String(e.uid),n);t===av.AUDIO?(e._audioTrack?e._audioTrack._updateOriginMediaStreamTrack(s):(e._audioTrack=new Nw(s,e.uid,e._uintid,this.store),jC.info(\"[\".concat(this.store.clientId,\"] [\").concat(this.store.p2pId,\"] create remote audio track: \").concat(e._audioTrack.getTrackId()))),a&&e._audioTrack._updateRtpTransceiver(a),this.bindRemoteTrackEvents(e,e._audioTrack)):(e._videoSSRC=i,e._videoTrack?e._videoTrack._updateOriginMediaStreamTrack(s):(e._videoTrack=new Ow(s,e.uid,e._uintid,this.store),jC.info(\"[\".concat(this.store.clientId,\"] [\").concat(this.store.p2pId,\"] create remote video track: \").concat(e._videoTrack.getTrackId()))),a&&e._videoTrack._updateRtpTransceiver(a),this.bindRemoteTrackEvents(e,e._videoTrack));const c=this.remoteUserMap.get(e);c?c.set(t,o):this.remoteUserMap.set(e,new Map([[t,o]])),this.statsCollector.addRemoteStats(e.uid),this.statsUploader.startUploadInboundStats(),this.startUploadDownlinkState();const d=this.pendingRemoteTracks.findIndex((i=>{let{user:n,kind:r}=i;return n.uid===e.uid&&t===r}));-1!==d&&(this.pendingRemoteTracks.splice(d,1),this.emit(hv.MediaReconnectEnd,e.uid))}async mockSubscribe(e,t,i,n){if(!this.recvConnection)throw new Kg(Hg.INVALID_OPERATION,\"Cannot subscribe remote user when recvConnection disconnected.\");await this.recvConnection.mockReceive(t,[{ssrcId:i}],String(e.uid),n)}async unsubscribe(e,t,i){const n=this.pendingRemoteTracks.filter((i=>{let{user:n,kind:r}=i;return void 0!==t?n.uid===e.uid&&t===r:n.uid===e.uid}));if(n.forEach((e=>{const t=this.pendingRemoteTracks.indexOf(e);this.pendingRemoteTracks.splice(t,1)})),this.recvConnection||i||n.forEach((t=>{let{kind:i}=t;var n;if(i===av.AUDIO)null===(n=e._audioTrack)||void 0===n||n._destroy(),e._audioTrack=void 0;else if(i===av.VIDEO){var r;null===(r=e._videoTrack)||void 0===r||r._destroy(),e._videoTrack=void 0}})),!this.recvConnection)return;const r=this.filterTobeUnSubscribedTracks(e,t);0!==r.length&&(await this.recvConnection.stopReceiving(r.map((e=>{let[,{id:t}]=e;return t}))),this.withdrawRemoteTracks(r),0===this.remoteUserMap.size&&(this.statsUploader.stopUploadInboundStats(),this.stopUploadDownlinkState()),r.forEach((e=>{let[t,{kind:n}]=e;var r,s;n===av.VIDEO&&t._videoSSRC&&(null===(r=this.recvConnection)||void 0===r||r.setStatsRemoteVideoIsReady(t._videoSSRC,!1));if(n===av.VIDEO)this.unbindRemoteTrackEvents(t._videoTrack),i||(null===(s=t._videoTrack)||void 0===s||s._destroy(),t._videoTrack=void 0);else if(n===av.AUDIO){var o;if(this.unbindRemoteTrackEvents(t._audioTrack),!i)null===(o=t._audioTrack)||void 0===o||o._destroy(),t._audioTrack=void 0}})),r.forEach((e=>{let[,{kind:t}]=e;yT(this,hv.RequestP2PMuteRemote,t)})))}startUploadDownlinkState(){if(this.uploadDownlinkStarted)return;this.uploadDownlinkStarted=!0,this.downlinkStatsUploadInterval&&window.clearInterval(this.downlinkStatsUploadInterval);const e=()=>Array.from(this.remoteUserMap.entries()).forEach((e=>{let[,t]=e;[av.VIDEO,av.AUDIO].forEach((e=>{t.has(e)?yT(this,hv.RequestP2PUnmuteRemote,e):yT(this,hv.RequestP2PMuteRemote,e)}))}));e(),this.downlinkStatsUploadInterval=window.setInterval((()=>{e()}),3e3)}stopUploadDownlinkState(){this.uploadDownlinkStarted&&(this.uploadDownlinkStarted=!1,this.downlinkStatsUploadInterval&&window.clearInterval(this.downlinkStatsUploadInterval))}getAllDataChannels(){return this.localDataChannels}async massSubscribe(e){throw new Kg(Hg.NOT_SUPPORTED,\"p2p mode does not support massSubscribe.\")}async massSubscribeNoLock(e){throw new Kg(Hg.NOT_SUPPORTED,\"p2p mode does not support massSubscribeNoLock.\")}async massUnsubscribe(e){throw new Kg(Hg.NOT_SUPPORTED,\"p2p mode does not support massUnsubscribe.\")}async massUnsubscribeNoLock(e){throw new Kg(Hg.NOT_SUPPORTED,\"p2p mode does not support massUnsubscribeNoLock.\")}async muteRemote(e,t){if(!this.recvConnection)return;const i=this.remoteUserMap.get(e);if(!i)return void jC.warning(\"[\".concat(this.store.clientId,\"] P2PChannel2.muteRemote has no remote user \").concat(e.uid,\".\"));if(!i.get(t))return void jC.warning(\"[\".concat(this.store.clientId,\"] P2PChannel2.muteRemote has no remote user \").concat(e.uid,\" media type \").concat(t,\".\"));const n=t===av.VIDEO?e._videoSSRC:e._audioSSRC;void 0!==n&&this.recvConnection.setStatsRemoteVideoIsReady(n,!1)}async unmuteRemote(e,t){return this.unmuteRemoteNoLock(e,t)}async unmuteRemoteNoLock(e,t){if(!this.recvConnection)return;const i=this.remoteUserMap.get(e);if(!i)return void jC.warning(\"[\".concat(this.store.clientId,\"] P2PChannel2.unmuteRemote has no remote user \").concat(e.uid,\".\"));i.get(t)||jC.warning(\"[\".concat(this.store.clientId,\"] P2PChannel2.unmuteRemote has no remote user \").concat(e.uid,\" media type \").concat(t,\".\"))}getAllTracks(e){const t=this.localTrackMap.get(lv.LocalAudioTrack);if((null==t?void 0:t.track)instanceof nw){const i=t.track;return Array.from(this.localTrackMap.entries()).filter((e=>{let[t]=e;return t!==lv.LocalAudioTrack})).filter((t=>{let[i]=t;return!(e&&i===lv.LocalVideoLowTrack)})).map((e=>{let[,{track:t}]=e;return t})).concat(i.trackList)}return Array.from(this.localTrackMap.entries()).filter((t=>{let[i]=t;return!(e&&i===lv.LocalVideoLowTrack)})).map((e=>{let[,{track:t}]=e;return t}))}reportPublishEvent(e,t,i,n,r){if(e){const i=this.localTrackMap.get(lv.LocalAudioTrack),s=n?this.localTrackMap.get(lv.LocalVideoLowTrack):this.localTrackMap.get(lv.LocalVideoTrack);eI.publish(this.store.sessionId,{eventElapse:RU.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:e,ec:t,audioName:null==i?void 0:i.track.getTrackLabel(),videoName:null==s?void 0:s.track.getTrackLabel(),screenshare:-1!==(null==s?void 0:s.track._hints.indexOf(jA.SCREEN_TRACK)),audio:!!i,video:!!s,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r})}else{var s;i||(i=[]);const o=i.find((e=>e instanceof ew)),a=n?null===(s=this.localTrackMap.get(lv.LocalVideoTrack))||void 0===s?void 0:s.track:i.find((e=>e instanceof Rw));eI.publish(this.store.sessionId,{eventElapse:RU.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:e,ec:t,audioName:null==o?void 0:o.getTrackLabel(),videoName:null==a?void 0:a.getTrackLabel(),screenshare:-1!==(null==a?void 0:a._hints.indexOf(jA.SCREEN_TRACK)),audio:!!o,video:!!a,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r})}}reportSubscribeEvent(e,t,i,n){const r=n===av.VIDEO?i._videoSSRC:i._audioSSRC;r&&eI.subscribe(this.store.sessionId,{succ:e,ec:t,video:n===av.VIDEO,audio:n===av.AUDIO,peerid:i.uid,subscribeRequestid:n===av.VIDEO?i._videoSSRC:i._audioSSRC,p2pid:this.store.p2pId,eventElapse:RU.measureFromSubscribeStart(this.store.clientId,r)})}reset(){jC.debug(\"[\".concat(this.store.clientId,\"] P2PChannel2.reset\")),this.sendMutex=new pS(\"P2PChannel2-send-mutex\"),this.sendMutex=new pS(\"P2PChannel2-recv-mutex\"),this.sendConnection&&(this.sendConnection.close(),this.unbindConnectionEvents(this.sendConnection),this.sendConnection=void 0),this.recvConnection&&(this.recvConnection.close(),this.unbindConnectionEvents(this.recvConnection),this.recvConnection=void 0),this.statsUploader.stopUploadOutboundStats(),this.statsUploader.stopUploadInboundStats(),this.statsUploader.stopUploadTransportStats(),this.statsUploader.stopUploadExtensionUsageStats(),this.stopUploadUplinkState(),this.stopUploadDownlinkState(),this.unbindLocalTrackEvents(),this.unbindAllRemoteTrackEvents(),this.unbindRtpTransceiver();const e=this.localTrackMap.get(lv.LocalAudioTrack);if((null==e?void 0:e.track)instanceof nw){if(e.track.trackList.length>0){const t=e.track;e.track.trackList.forEach((e=>{t.removeAudioTrack(e)}))}e.track.close()}this.localTrackMap.clear(),this.remoteUserMap.clear(),this.statsCollector.removeRemoteStats(),this.statsCollector.removeLocalStats(),this.dtlsFailedCount=0,this.pendingLocalTracks=[],this.pendingRemoteTracks=[],this.reconnectInterval&&(window.clearInterval(this.reconnectInterval),this.reconnectInterval=void 0),this.state=uv.Disconnected}getStats(e){var t,i;return e?null===(i=this.recvConnection)||void 0===i?void 0:i.getStats():null===(t=this.sendConnection)||void 0===t?void 0:t.getStats()}getRemoteVideoIsReady(e){var t;return(null===(t=this.recvConnection)||void 0===t?void 0:t.getRemoteVideoIsReady(e))||!1}getLocalAudioVolume(){const e=this.localTrackMap.get(lv.LocalAudioTrack);if(e)return e.track.getVolumeLevel()}getLocalVideoSize(){const e=this.localTrackMap.get(lv.LocalVideoTrack);if(e)return{width:e.track._videoWidth||0,height:e.track._videoHeight||0}}getEncoderConfig(e){const t=this.localTrackMap.get(e);return t&&t.track instanceof Rw||t&&t.track instanceof ew?t.track._encoderConfig:void 0}getLocalMedia(e){return this.localTrackMap.get(e)}hasLocalMedia(){return this.localTrackMap.size>0}hasRemoteMedia(e,t){if(!e)return this.remoteUserMap.size>0;const i=this.remoteUserMap.get(e);return!!i&&(!t||i.has(t))}async hasRemoteMediaWithLock(e,t){if(!e)return this.remoteUserMap.size>0;const i=this.remoteUserMap.get(e);return!!i&&(!t||i.has(t))}getRemoteMedia(e){var t;const i=Array.from(ph(t=this.remoteUserMap).call(t)).find((t=>t.uid===e));return i?{audioTrack:i.audioTrack,audioSSRC:i._audioSSRC,videoTrack:i.videoTrack,videoSSRC:i._videoSSRC}:{}}getAudioLevels(){let e=Array.from(this.remoteUserMap.entries()).map((e=>{let[t]=e;return{uid:t.uid,level:t.audioTrack?100*t.audioTrack._source.getAccurateVolumeLevel():0}}));const t=this.localTrackMap.get(lv.LocalAudioTrack);return t&&e.push({level:100*t.track._source.getAccurateVolumeLevel(),uid:this.store.uid}),e=ep(e).call(e,((e,t)=>e.level-t.level)),e}async disconnectForReconnect(){this.sendConnection&&this.recvConnection&&(jC.debug(\"[\".concat(this.store.clientId,\"] P2PChannel2.disconnectForReconnect closing P2PConnection\")),this.state=uv.Reconnecting,RC(\"KEEP_LAST_FRAME\")&&0!==this.remoteUserMap.size&&Array.from(this.remoteUserMap.entries()).forEach((e=>{let[t]=e;var i;t._videoTrack&&t._videoTrack._player&&(null===(i=t._videoTrack._player.getVideoElement())||void 0===i||i.pause(),t._videoTrack._player.isKeepLastFrame=!0,t._videoTrack._originMediaStreamTrack.stop())})),this.sendConnection.close(),this.unbindConnectionEvents(this.sendConnection),this.sendConnection=void 0,this.recvConnection.close(),this.unbindConnectionEvents(this.recvConnection),this.recvConnection=void 0,0!==this.localTrackMap.size&&(Array.from(this.localTrackMap.entries()).forEach((e=>{var t;let[i,{track:n}]=e;switch(i){case lv.LocalVideoTrack:bn(t=n._hints).call(t,jA.LOW_STREAM)?n.close():this.pendingLocalTracks.push(n);break;case lv.LocalAudioTrack:n instanceof nw?this.pendingLocalTracks=this.pendingLocalTracks.concat(n.trackList):this.pendingLocalTracks.push(n);case lv.LocalVideoLowTrack:}})),this.emit(hv.MediaReconnectStart,this.store.uid)),this.unbindLocalTrackEvents(),this.localTrackMap.clear(),0!==this.remoteUserMap.size&&Array.from(this.remoteUserMap.entries()).forEach((e=>{let[t,i]=e;Array.from(ph(i).call(i)).forEach((e=>{this.setPendingRemoteMedia(t,e)})),this.emit(hv.MediaReconnectStart,t.uid)})),this.unbindAllRemoteTrackEvents(),this.remoteUserMap.clear(),this.stopUploadUplinkState(),this.stopUploadDownlinkState(),this.statsUploader.stopUploadOutboundStats(),this.statsUploader.stopUploadInboundStats(),this.statsUploader.stopUploadTransportStats(),jC.debug(\"[\".concat(this.store.clientId,\"] P2PChannel2 disconnected, waiting to reconnect.\")))}hasPendingRemoteMedia(e,t){for(const i of this.pendingRemoteTracks){const{user:n,kind:r}=i;if((e instanceof sV?e.uid:e)===n.uid&&t===r)return!0}return!1}setPendingRemoteMedia(e,t){this.hasPendingRemoteMedia(e,t)||this.pendingRemoteTracks.push({user:e,kind:t})}async restartICE(e,t){let i,n;if(e===TI.SEND_ONLY){if(!this.sendConnection)throw new Kg(Hg.INVALID_OPERATION,\"Cannot call P2PChannel2.handleMuteLocalTrack before sendConnection established.\");i=await this.sendMutex.lock(\"From P2PChannel.restartICE\"),n=this.sendConnection}else{if(!this.recvConnection)throw new Kg(Hg.INVALID_OPERATION,\"Cannot call P2PChannel2.handleMuteLocalTrack before recvConnection established.\");i=await this.recvMutex.lock(\"From P2PChannel.restartICE\"),n=this.recvConnection}try{if(t){const e=await n.restartICE(t);return n.isInRestartIce=!1,e}{const e=await n.restartICE();if(e){const t=await vT(this,hv.RequestP2PRestartICE,{direction:TI.RECEIVE_ONLY,iceParameter:e});await n.restartICE(t),n.isInRestartIce=!1}}}finally{i()}}getUplinkNetworkQuality(){if(!this.sendConnection)return 0;const e=this.sendConnection.getStats(),t=this.localTrackMap.get(lv.LocalVideoTrack),i=this.localTrackMap.get(lv.LocalAudioTrack),n=e.videoSend.find((e=>{var i;return e.ssrc===(null==t||null===(i=t.ssrcs)||void 0===i?void 0:i[0].ssrcId)})),r=e.audioSend.find((e=>{var t;return e.ssrc===(null==i||null===(t=i.ssrcs)||void 0===t?void 0:t[0].ssrcId)}));if(!n||!r)return 1;const s=AT(this,hv.NeedSignalRTT),o=n?n.rttMs:void 0,a=r?r.rttMs:void 0,c=o&&a?(o+a)/2:o||a,d=(c&&s?(c+s)/2:c||s)||0,l=100*e.sendPacketLossRate*.7/50+.3*d/1500,u=l<.17?1:l<.36?2:l<.59?3:l<.1?4:5,h=null==t?void 0:t.track;if(h&&h._encoderConfig&&-1===h._hints.indexOf(jA.SCREEN_TRACK)){const t=h._encoderConfig.bitrateMax,i=e.bitrate.actualEncoded;if(t&&i){const e=(1e3*t-i)/(1e3*t);return nI[e<.15?0:e<.3?1:e<.45?2:e<.6?3:4][u]}}return u}getDownlinkNetworkQuality(){if(!this.recvConnection)return 0;const e=this.recvConnection.getStats();let t=0;return Array.from(this.remoteUserMap.entries()).forEach((i=>{let[n]=i;const r=n._audioSSRC,s=n._videoSSRC,o=e.audioRecv.find((e=>e.ssrc===r)),a=e.videoRecv.find((e=>e.ssrc===s));if(!o&&!a)return void(t+=1);const c=AT(this,hv.NeedSignalRTT),d=e.rtt,l=(d&&c?(d+c)/2:d||c)||0,u=o?o.jitterMs:void 0,h=e.recvPacketLossRate;let p=.7*h*100/50+.3*l/1500;u&&(p=.6*h*100/50+.2*l/1500+.2*u/400);t+=p<.1?1:p<.17?2:p<.36?3:p<.59?4:5})),this.remoteUserMap.size>0?Math.round(t/this.remoteUserMap.size):t}async muteLocalTrack(e){return new cg(((t,i)=>{this.handleMuteLocalTrack(e,t,i)}))}filterTobePublishedTracks(e,t,i){const n=[],r=IA(),s=this.getAllTracks();e=HT(e=e.filter((e=>-1===s.indexOf(e))));let o=!1,a=!1;for(const s of e){if(s instanceof Rw&&(this.localTrackMap.has(lv.LocalVideoTrack)||o?new Kg(Hg.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS).throw():(n.push({track:s,type:lv.LocalVideoTrack}),o=!0),t)){const e=this.getLowVideoTrack(s,i);n.push({track:e,type:lv.LocalVideoLowTrack})}if(s instanceof ew){const e=this.localTrackMap.get(lv.LocalAudioTrack);if(e){if(!(e.track instanceof nw))throw new Kg(Hg.NOT_SUPPORTED,\"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser does not support audio mixing\");if(s._bypassWebAudio)throw new Kg(Hg.NOT_SUPPORTED,\"cannot publish multiple tracks which one of them configured with bypassWebAudio\");e.track.addAudioTrack(s),this.bindLocalAudioTrackEvents(s,!0)}else if(a){const e=n.find((e=>{let{type:t}=e;return t===lv.LocalAudioTrack}));if(!(e.track instanceof nw))throw new Kg(Hg.NOT_SUPPORTED,\"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser does not support audio mixing\");if(s._bypassWebAudio)throw new Kg(Hg.NOT_SUPPORTED,\"cannot publish multiple tracks which one of them configured with bypassWebAudio\");e.track.addAudioTrack(s)}else{if(!r.webAudioMediaStreamDest||s instanceof nw||s._bypassWebAudio)n.push({track:s,type:lv.LocalAudioTrack});else{const e=new nw;e.addAudioTrack(s),n.push({track:e,type:lv.LocalAudioTrack})}a=!0}}}return n}filterTobeUnpublishedTracks(e){const t=[],i=this.getAllTracks();e=HT(e=e.filter((e=>-1!==i.indexOf(e))));for(const i of e){if(i instanceof ew){const e=this.localTrackMap.get(lv.LocalAudioTrack);if(!e)continue;e.track instanceof nw?(e.track.removeAudioTrack(i),this.unbindLocalAudioTrackEvents(i),0===e.track.trackList.length&&(t.push([lv.LocalAudioTrack,e]),e.track.close())):t.push([lv.LocalAudioTrack,e])}if(i instanceof Rw){const e=this.localTrackMap.get(lv.LocalVideoTrack);if(!e)continue;t.push([lv.LocalVideoTrack,e]);const i=this.localTrackMap.get(lv.LocalVideoLowTrack);i&&t.push([lv.LocalVideoLowTrack,i])}}return t}bindLocalTrackEvents(e){e.forEach((e=>{let{track:t,type:i}=e;switch(i){case lv.LocalVideoTrack:t.addListener(BA.GET_STATS,this.handleGetLocalVideoStats),t.addListener(BA.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.addListener(BA.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.addListener(BA.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.addListener(BA.SET_OPTIMIZATION_MODE,this.handleSetOptimizationMode),t.addListener(BA.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.addListener(BA.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.addListener(BA.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case lv.LocalAudioTrack:this.bindLocalAudioTrackEvents(t);case lv.LocalVideoLowTrack:}}))}bindLocalAudioTrackEvents(e,t){e instanceof nw?e.trackList.forEach((e=>{e.addListener(BA.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(BA.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(BA.GET_STATS,this.handleGetLocalAudioStats),e.addListener(BA.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(BA.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)})):(e.addListener(BA.GET_STATS,this.handleGetLocalAudioStats),e.addListener(BA.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(BA.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(BA.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(BA.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack),t||e.addListener(BA.NEED_REPLACE_TRACK,this.handleReplaceTrack))}unbindLocalTrackEvents(e){e||(e=Array.from(this.localTrackMap.entries()).map((e=>{let[t,{track:i}]=e;return{track:i,type:t}}))),e.forEach((e=>{let{track:t,type:i}=e;switch(i){case lv.LocalVideoTrack:t.off(BA.GET_STATS,this.handleGetLocalVideoStats),t.off(BA.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.off(BA.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.off(BA.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.off(BA.SET_OPTIMIZATION_MODE,this.handleSetOptimizationMode),t.off(BA.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.off(BA.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.off(BA.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case lv.LocalAudioTrack:this.unbindLocalAudioTrackEvents(t);case lv.LocalVideoLowTrack:}}))}unbindLocalAudioTrackEvents(e){e instanceof nw?e.trackList.forEach((e=>{e.off(BA.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(BA.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(BA.GET_STATS,this.handleGetLocalAudioStats),e.off(BA.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(BA.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)})):(e.off(BA.GET_STATS,this.handleGetLocalAudioStats),e.off(BA.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(BA.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(BA.NEED_REPLACE_TRACK,this.handleReplaceTrack),e.off(BA.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(BA.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack))}bindRemoteTrackEvents(e,t){t instanceof Ow&&t.addListener(BA.GET_STATS,(t=>{t(this.handleGetRemoteVideoStats(e))})),t instanceof Nw&&t.addListener(BA.GET_STATS,(t=>{t(this.handleGetRemoteAudioStats(e))}))}unbindRemoteTrackEvents(e){e&&e.removeAllListeners(BA.GET_STATS)}unbindAllRemoteTrackEvents(){Array.from(this.remoteUserMap.entries()).forEach((e=>{let[t,i]=e;i.has(av.AUDIO)&&this.unbindRemoteTrackEvents(t._audioTrack),i.has(av.VIDEO)&&this.unbindRemoteTrackEvents(t._videoTrack)}))}createGatewayPublishMessage(e,t){return e.map(((e,i)=>{var n;let r,{track:s,type:o}=e;switch(o){case lv.LocalAudioTrack:r=JI.Audio;break;case lv.LocalVideoTrack:r=bn(n=s._hints).call(n,jA.SCREEN_TRACK)?JI.Screen:JI.High;break;case lv.LocalVideoLowTrack:r=JI.Low}return{kind:o===lv.LocalAudioTrack?av.AUDIO:av.VIDEO,stream_type:r,mid:t[i].id,ssrcs:t[i].localSSRC,isMuted:s.muted||!s.enabled}}))}createGatewayUnpublishMessage(e){return e.map((e=>{var t;let i,[n,{track:r,ssrcs:s,id:o}]=e;switch(n){case lv.LocalVideoTrack:i=bn(t=r._hints).call(t,jA.SCREEN_TRACK)?JI.Screen:JI.High;break;case lv.LocalAudioTrack:i=JI.Audio;break;case lv.LocalVideoLowTrack:i=JI.Low}return{stream_type:i,ssrcs:s,mid:o}}))}assignLocalTracks(e,t){e.forEach(((e,i)=>{let{track:n,type:r}=e;this.localTrackMap.set(r,{track:n,id:t[i].id,ssrcs:t[i].localSSRC})}))}withdrawLocalTracks(e){e.forEach((e=>{let[t]=e;this.localTrackMap.delete(t)}))}bindConnectionEvents(e){e.onConnectionStateChange=async t=>{var i;jC.info(\"[\".concat(this.store.clientId,\"] [p2pId: \").concat(this.store.p2pId,\"]: \").concat(e.name,\".onConnectionStateChange(\").concat(t,\")\")),this.emit(hv.PeerConnectionStateChange,t),\"connected\"!==t||this.store.keyMetrics.peerConnectionEnd||this.store.peerConnectionEnd(),\"connected\"===t&&(e.isInRestartIce=!1),bn(i=this._restartStates).call(i,t)&&!e.isInRestartIce&&(\"disconnected\"===t&&await iS(800),\"disconnected\"!==e.iceConnectionState&&\"failed\"!==e.iceConnectionState||this.handleDisconnect(e.direction))},e.onICEConnectionStateChange=e=>{\"connected\"!==e||this.store.keyMetrics.iceConnectionEnd||this.store.iceConnectionEnd(),jC.info(\"[\".concat(this.store.clientId,\"] [p2pId: \").concat(this.store.p2pId,\"]: P2PConnection.onICEConnectionStateChange(\").concat(e,\")\")),eI.reportApiInvoke(this.store.sessionId,{name:\"ICEConnectionStateChange\",options:e,tag:pT.TRACER}).onSuccess(),this.emit(hv.IceConnectionStateChange,e)},e.onICETransportStateChange=e=>{jC.info(\"[\".concat(this.store.clientId,\"] [p2pId: \").concat(this.store.p2pId,\"]: P2PConnection.onICETransportStateChange(\").concat(e,\")\"))},e.onDTLSTransportStateChange=e=>{jC.info(\"[\".concat(this.store.clientId,\"] [p2pId: \").concat(this.store.p2pId,\"]: P2PConnection.onDTLSTransportStateChange(\").concat(e,\")\"))},e.onDTLSTransportError=e=>{jC.info(\"[\".concat(this.store.clientId,\"] [p2pId: \").concat(this.store.p2pId,\"]: P2PConnection.onDTLSTransportError(\").concat(e,\")\"))},e.onFirstAudioDecoded=e=>{var t;const i=Array.from(ph(t=this.remoteUserMap).call(t)).find((t=>t._audioSSRC===e));var n;i&&(this.store.subscribe(i.uid,\"audio\",void 0,void 0,void 0,Date.now()),null===(n=i.audioTrack)||void 0===n||n.emit(qA.FIRST_FRAME_DECODED),eI.firstRemoteFrame(this.store.sessionId,YC.FIRST_AUDIO_DECODE,qC.FIRST_AUDIO_DECODE,{peer:i._uintid,subscribeElapse:RU.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId}))},e.onFirstAudioReceived=e=>{var t;const i=Array.from(ph(t=this.remoteUserMap).call(t)).find((t=>t._audioSSRC===e));i&&eI.firstRemoteFrame(this.store.sessionId,YC.FIRST_AUDIO_RECEIVED,qC.FIRST_AUDIO_RECEIVED,{peer:i._uintid,subscribeElapse:RU.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId})},e.onFirstVideoDecoded=(e,t,i)=>{this.reportVideoFirstFrameDecoded(e,t,i)},e.onFirstVideoReceived=e=>{var t;const i=Array.from(ph(t=this.remoteUserMap).call(t)).find((t=>t._videoSSRC===e));i&&eI.firstRemoteFrame(this.store.sessionId,YC.FIRST_VIDEO_RECEIVED,qC.FIRST_VIDEO_RECEIVED,{peer:i._uintid,subscribeElapse:RU.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId})},e.onSelectedLocalCandidateChanged=(e,t)=>{const i=\"relay\"===e.candidateType,n=\"relay\"===t.candidateType;\"unknown\"!==t.candidateType&&i===n||this.emit(hv.ConnectionTypeChange,i),jC.info(\"[\".concat(this.store.clientId,\"] [p2pId: \").concat(this.store.p2pId,\"]: P2PConnection.SelectedLocalCandidateChanged(\").concat(JSON.stringify(Ay(t)),\" -> \").concat(JSON.stringify(Ay(e)),\")\"))},e.onSelectedRemoteCandidateChanged=(e,t)=>{jC.info(\"[\".concat(this.store.clientId,\"] [p2pId: \").concat(this.store.p2pId,\"]: P2PConnection.SelectedRemoteCandidateChanged(\").concat(JSON.stringify(Ay(t)),\" -> \").concat(JSON.stringify(Ay(e)),\")\"))},e.onFirstVideoDecodedTimeout=e=>{this.reportVideoFirstFrameDecoded(e,void 0,void 0,!0)},e.onLocalCandidate=t=>{this.emit(hv.LocalCandidate,{candidate:t,direction:e.direction})}}unbindConnectionEvents(e){e.onConnectionStateChange=void 0,e.onICEConnectionStateChange=void 0,e.onICETransportStateChange=void 0,e.onDTLSTransportStateChange=void 0,e.onDTLSTransportError=void 0,e.onFirstAudioDecoded=void 0,e.onFirstAudioReceived=void 0,e.onFirstVideoDecoded=void 0,e.onFirstVideoReceived=void 0,e.onSelectedLocalCandidateChanged=void 0,e.onSelectedRemoteCandidateChanged=void 0,e.onFirstVideoDecodedTimeout=void 0,e.onLocalCandidate=void 0}async handleDisconnect(e){const t=e===TI.SEND_ONLY?this.sendConnection:this.recvConnection;t&&!t.isInRestartIce&&(t.isInRestartIce=!0,jC.debug(\"[\".concat(this.store.clientId,\"] [P2PChannel-\").concat(t.name,\"] start use restartICE\")),e===TI.SEND_ONLY?this.restartICE(e):vT(this,hv.RequestP2PRestartICE,{direction:TI.SEND_ONLY}))}filterTobeMutedTracks(e){const t=[];if(-1===this.getAllTracks().indexOf(e))return t;const i=this.localTrackMap.get(lv.LocalAudioTrack);if(e instanceof ew&&(null==i?void 0:i.track)instanceof nw)return i.track.isActive||t.push([lv.LocalAudioTrack,i]),t;const n=Array.from(this.localTrackMap.entries()).find((t=>{let[,{track:i}]=t;return e===i}));if(n&&(t.push(n),n[0]===lv.LocalVideoTrack)){const e=this.localTrackMap.get(lv.LocalVideoLowTrack);e&&t.push([lv.LocalVideoLowTrack,e])}return t}filterTobeUnmutedTracks(e){const t=[],i=this.localTrackMap.get(lv.LocalAudioTrack);if(e instanceof ew&&(null==i?void 0:i.track)instanceof nw)return i.track.isActive&&t.push([lv.LocalAudioTrack,i]),t;const n=Array.from(this.localTrackMap.entries()).find((t=>{let[,{track:i}]=t;return e===i}));if(n)if(n[0]===lv.LocalVideoTrack){t.push(n);const e=this.localTrackMap.get(lv.LocalVideoLowTrack);e&&t.push([lv.LocalVideoLowTrack,e])}else t.push(n);return t}createMuteMessage(e){return e.map((e=>{var t;let i,[n,{track:r,ssrcs:s,id:o}]=e;switch(n){case lv.LocalAudioTrack:i=JI.Audio;break;case lv.LocalVideoTrack:i=bn(t=r._hints).call(t,jA.SCREEN_TRACK)?JI.Screen:JI.High;break;case lv.LocalVideoLowTrack:i=JI.Low}return{stream_type:i,ssrcs:s,mid:o}}))}createUnmuteMessage(e){return e.map((e=>{var t;let i,[n,{track:r,ssrcs:s,id:o}]=e;switch(n){case lv.LocalAudioTrack:i=JI.Audio;break;case lv.LocalVideoTrack:i=bn(t=r._hints).call(t,jA.SCREEN_TRACK)?JI.Screen:JI.High;break;case lv.LocalVideoLowTrack:i=JI.Low}return{stream_type:i,ssrcs:s,mid:o}}))}filterTobeUnSubscribedTracks(e,t){const i=[],n=this.remoteUserMap.get(e);if(!n)return i;if(t){const r=n.get(t);if(!r)return i;i.push([e,{kind:t,id:r}])}else Array.from(n.entries()).forEach((t=>{let[n,r]=t;i.push([e,{kind:n,id:r}])}));return i}createUnsubscribeMessage(e){const t=[];return e.forEach((e=>{let[i,{kind:n,id:r}]=e;switch(n){case av.VIDEO:return void(i._videoSSRC&&t.push({stream_type:av.VIDEO,ssrcId:i._videoSSRC}));case av.AUDIO:return void(i._audioSSRC&&t.push({stream_type:av.AUDIO,ssrcId:i._audioSSRC}))}})),t}withdrawRemoteTracks(e){e.forEach((e=>{let[t,{kind:i}]=e;const n=this.remoteUserMap.get(t);n&&(n.delete(i),0===Array.from(n.entries()).length&&this.remoteUserMap.delete(t))}))}async updateBitrateLimit(e){const t=this.localTrackMap.get(lv.LocalVideoTrack),i=this.localTrackMap.get(lv.LocalVideoLowTrack);t&&await t.track.setBitrateLimit(e.uplink),i&&e.low_stream_uplink&&await i.track.setBitrateLimit({max_bitrate:e.low_stream_uplink.bitrate,min_bitrate:e.low_stream_uplink.bitrate||0})}isP2PDisconnected(){if(this.sendConnection&&this.recvConnection){const e=this.sendConnection.peerConnectionState,t=this.recvConnection.peerConnectionState;return\"connected\"!==e&&\"connected\"!==t}return!0}async tryToUnmuteAudio(e){for(let t=0;tthis.getStats(e),this.statsUploader.requestLocalMedia=()=>Array.from(this.localTrackMap.entries()).filter((e=>{let[,{ssrcs:t}]=e;return!!t})),this.statsUploader.requestRemoteMedia=()=>Array.from(this.remoteUserMap.entries()),this.statsUploader.requestVideoIsReady=e=>{var t;return!(null===(t=this.recvConnection)||void 0===t||!t.getRemoteVideoIsReady(e))},this.statsUploader.requestUpload=(e,t)=>this.emit(hv.RequestUpload,e,t),this.statsUploader.requestUploadStats=e=>this.emit(hv.RequestUploadStats,e),this.statsUploader.requestAllTracks=()=>this.getAllTracks()}unbindStatsUploaderEvents(){this.statsUploader.requestStats=void 0,this.statsUploader.requestLocalMedia=void 0,this.statsUploader.requestRemoteMedia=void 0,this.statsUploader.requestVideoIsReady=void 0}async requestReconnect(){this.dtlsFailedCount+=1,await iS(mS(this.dtlsFailedCount,ES)),this.emit(hv.RequestReconnect)}async reconnectP2P(){}canPublishLowStream(){return this.localTrackMap.has(lv.LocalVideoTrack)||this.pendingLocalTracks.some((e=>e instanceof Rw))}throwIfTrackTypeNotMatch(e){if(e.filter((e=>e instanceof Rw)).length>1)throw new Kg(Hg.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(e.filter((e=>e instanceof ew)).length>1&&(e.some((e=>e instanceof ew&&e._bypassWebAudio))||!IA().webAudioMediaStreamDest))throw new Kg(Hg.NOT_SUPPORTED,\"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode\");for(const t of e){if(t instanceof Rw&&this.pendingLocalTracks.some((e=>e instanceof Rw)))throw new Kg(Hg.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(t instanceof ew&&this.pendingLocalTracks.some((e=>e instanceof ew))&&(!IA().webAudioMediaStreamDest||t._bypassWebAudio||this.pendingLocalTracks.some((e=>e instanceof ew&&e._bypassWebAudio))))throw new Kg(Hg.NOT_SUPPORTED,\"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode\")}}getLowVideoTrack(e,t){const i=!RC(\"DISABLE_DUAL_STREAM_USE_ENCODING\")&&IA().supportDualStreamEncoding,n=uV(uV({},{width:160,height:120,framerate:15,bitrate:50}),t);let r;r=i?e._mediaStreamTrack.clone():Gx(e,n);const s=nS(8,\"track-low-\"),o=new Rw(r,uV(uV({},i&&{scaleResolutionDownBy:yy(n,e)}),{},{frameRate:n.framerate,bitrateMax:n.bitrate,bitrateMin:n.bitrate}),void 0,void 0,s);return o.on(KA.TRANSCEIVER_UPDATED,(t=>{e._updateRtpTransceiver(t,GA.LOW_STREAM)})),o._hints.push(jA.LOW_STREAM),e.addListener(BA.NEED_CLOSE,(()=>{o.close()})),o}async globalLock(){return this.recvMutex.lock(\"From P2PChannel2.globalLock\")}reportVideoFirstFrameDecoded(e,t,i,n){var r;const s=Array.from(ph(r=this.remoteUserMap).call(r)).find((t=>t._videoSSRC===e));if(s){n||this.store.subscribe(s.uid,\"video\",void 0,void 0,void 0,void 0,Date.now());const r=this.store.keyMetrics,o=r.subscribe.find((e=>e.userId===s.uid&&\"video\"===e.type));eI.firstRemoteVideoDecode(this.store.sessionId,YC.FIRST_VIDEO_DECODE,qC.FIRST_VIDEO_DECODE,{peer:s._uintid,videowidth:t,videoheight:i,subscribeElapse:RU.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId,apEnd:r.requestAPEnd||0,apStart:r.requestAPStart||0,joinGwEnd:r.joinGatewayEnd||0,joinGwStart:r.joinGatewayStart||0,pcEnd:r.peerConnectionEnd||0,pcStart:r.peerConnectionStart||0,subscriberEnd:(null==o?void 0:o.subscribeEnd)||0,subscriberStart:(null==o?void 0:o.subscribeStart)||0,videoAddNotify:(null==o?void 0:o.streamAdded)||0,state:n?1:0})}}async remoteMediaSsrcChanged(e,t,i){if(!this.recvConnection)return!1;const n=this.remoteUserMap.get(e);if(!n)return!1;const r=n.get(t);if(!r)return!1;const s=await this.recvConnection.getRemoteSSRC(r);return void 0!==s&&s!==i}resetConnection(e){jC.debug(\"[\".concat(this.store.clientId,\"] [P2PChannel2] reset connection to \").concat(e)),this.state===uv.Connected?(jC.debug(\"[\".concat(this.store.clientId,\"] [P2PChannel2] fallback to websocket but P2PChannel2 state still connected, disconnect first\")),this.disconnectForReconnect()):(this.sendConnection&&(this.sendConnection.close(),this.unbindConnectionEvents(this.sendConnection),this.sendConnection=void 0),this.recvConnection&&(this.recvConnection.close(),this.unbindConnectionEvents(this.recvConnection),this.recvConnection=void 0))}async publishDataChannel(e){throw new Kg(Hg.NOT_SUPPORTED)}async unpublishDataChannel(e){throw new Kg(Hg.NOT_SUPPORTED)}async subscribeDataChannel(e,t){throw new Kg(Hg.NOT_SUPPORTED)}async unsubscribeDataChannel(e,t){throw new Kg(Hg.NOT_SUPPORTED)}hasPendingRemoteDataChannel(e,t){throw new Kg(Hg.NOT_SUPPORTED)}setPendingRemoteDataChannel(e,t){throw new Kg(Hg.NOT_SUPPORTED)}async preConnect(e,t,i,n,r,s){throw new Kg(Hg.NOT_SUPPORTED)}getEstablishParams(){throw new Kg(Hg.NOT_SUPPORTED)}async reSubscribe(e){throw new Kg(Hg.NOT_SUPPORTED)}async updateVideoStreamParameter(e,t){throw new Kg(Hg.NOT_SUPPORTED)}unbindRtpTransceiver(){0!==this.localTrackMap.size&&Array.from(this.localTrackMap.entries()).forEach((e=>{let[t,{track:i}]=e;t===lv.LocalVideoLowTrack?i._updateRtpTransceiver(void 0,GA.LOW_STREAM):i._updateRtpTransceiver(void 0)}))}}function pV(e){return function(t,i,n){const r=t[i];if(\"function\"!=typeof r)throw new Error(\"Cannot use mutex on object property.\");return n.value=async function(){for(var t=arguments.length,n=new Array(t),s=0;s{this.p2pChannel&&(this.updateRemoteStats(this.p2pChannel),this.updateLocalStats(this.p2pChannel))})),this.store=e,this.updateStatsInterval=window.setInterval(this.updateStats,1e3),this.exceptionMonitor=new TU,this.exceptionMonitor.on(\"exception\",((e,t,i)=>{this.onStatsException&&this.onStatsException(e,t,i)}))}reset(){this.localStats=new Map,this.remoteStats=new Map,this.trafficStats=void 0,this.trafficStatsPeerList=[],this.uplinkStats=void 0}getLocalAudioTrackStats(){return this.localStats.get(lv.LocalAudioTrack)||EV({},XA)}getLocalVideoTrackStats(){return this.localStats.get(lv.LocalVideoTrack)||EV({},QA)}getRemoteAudioTrackStats(e){const t=(e,t)=>{if(!this.trafficStats)return t;const i=this.trafficStats.peer_delay.find((t=>t.peer_uid===e));return i&&(t.publishDuration=i.B_ppad+(Date.now()-this.trafficStats.timestamp)),t},i={};if(e){var n;const r=null===(n=this.remoteStats.get(e))||void 0===n?void 0:n.audioStats;r&&(i[e]=t(e,r))}else Array.from(this.remoteStats.entries()).forEach((e=>{let[n,{audioStats:r}]=e;r&&(i[n]=t(n,r))}));return i}getRemoteNetworkQualityStats(e){const t={};if(e){var i;const n=null===(i=this.remoteStats.get(e))||void 0===i?void 0:i.networkStats;n&&(t[e]=n)}else Array.from(this.remoteStats.entries()).forEach((e=>{let[i,{networkStats:n}]=e;n&&(t[i]=n)}));return t}getRemoteVideoTrackStats(e){const t=(e,t)=>{if(!this.trafficStats)return t;const i=this.trafficStats.peer_delay.find((t=>t.peer_uid===e));return i&&(t.publishDuration=i.B_ppvd+(Date.now()-this.trafficStats.timestamp)),t},i={};if(e){var n;const r=null===(n=this.remoteStats.get(e))||void 0===n?void 0:n.videoStats;r&&(i[e]=t(e,r))}else Array.from(this.remoteStats.entries()).forEach((e=>{let[n,{videoStats:r}]=e;r&&(i[n]=t(n,r))}));return i}getRTCStats(){let e=0,t=0,i=0,n=0;const r=this.localStats.get(lv.LocalAudioTrack);r&&(e+=r.sendBytes,t+=r.sendBitrate);const s=this.localStats.get(lv.LocalVideoTrack);s&&(e+=s.sendBytes,t+=s.sendBitrate);const o=this.localStats.get(lv.LocalVideoLowTrack);o&&(e+=o.sendBytes,t+=o.sendBitrate),this.remoteStats.forEach((e=>{let{audioStats:t,videoStats:r}=e;t&&(i+=t.receiveBytes,n+=t.receiveBitrate),r&&(i+=r.receiveBytes,n+=r.receiveBitrate)}));let a=1;return this.trafficStats&&(a+=this.trafficStats.peer_delay.length),{Duration:0,UserCount:a,SendBitrate:t,SendBytes:e,RecvBytes:i,RecvBitrate:n,OutgoingAvailableBandwidth:this.uplinkStats?this.uplinkStats.B_uab/1e3:0,RTT:this.trafficStats?2*this.trafficStats.B_acd:0}}addLocalStats(e){this.localStats.set(e,void 0)}removeLocalStats(e){e?this.localStats.delete(e):this.localStats.clear()}addRemoteStats(e){this.remoteStats.set(e,{})}removeRemoteStats(e){e?this.remoteStats.delete(e):this.remoteStats.clear()}addP2PChannel(e){this.p2pChannel=e}updateTrafficStats(e){e.peer_delay=e.peer_delay.filter((e=>void 0!==e.B_ppad||void 0!==e.B_ppvd));e.peer_delay.filter((e=>-1===this.trafficStatsPeerList.indexOf(e.peer_uid))).forEach((e=>{var t;const i=null===(t=this.p2pChannel)||void 0===t?void 0:t.getRemoteMedia(e.peer_uid),n=null!=i&&i.videoSSRC?RU.measureFromSubscribeStart(this.store.clientId,i.videoSSRC):0,r=null!=i&&i.audioSSRC?RU.measureFromSubscribeStart(this.store.clientId,i.audioSSRC):0;void 0!==e.B_ppad&&void 0!==e.B_ppvd&&(this.onUploadPublishDuration&&this.onUploadPublishDuration(e.peer_uid,e.B_ppad,e.B_ppvd,n>r?n:r),this.trafficStatsPeerList.push(e.peer_uid))})),this.trafficStats=e}updateUplinkStats(e){this.uplinkStats&&this.uplinkStats.B_fir!==e.B_fir&&jC.debug(\"[\".concat(this.store.clientId,\"]: Period fir changes to \").concat(e.B_fir)),this.uplinkStats=e}static isRemoteVideoFreeze(e,t,i){if(!e)return!1;const n=!!i&&t.framesDecodeFreezeTime>i.framesDecodeFreezeTime,r=!i||t.framesDecodeCount>i.framesDecodeCount;return n||!r}static isRemoteAudioFreeze(e){return!!e&&e._isFreeze()}isLocalVideoFreeze(e){return!(!e.inputFrame||!e.sentFrame)&&(e.inputFrame.frameRate>5&&e.sentFrame.frameRate<3)}updateLocalStats(e){Array.from(this.localStats.entries()).forEach((t=>{let[i,n]=t;switch(i){case lv.LocalVideoTrack:case lv.LocalVideoLowTrack:{const t=n,s=EV({},QA),o=e.getStats(),a=e.getLocalMedia(i);if(o){const i=o.videoSend.find((e=>e.ssrc===(null==a?void 0:a.ssrcs[0].ssrcId)));if(i){const n=e.getLocalVideoSize(),r=e.getEncoderConfig(lv.LocalVideoTrack);\"H264\"!==i.codec&&\"H265\"!==i.codec&&\"VP8\"!==i.codec&&\"VP9\"!==i.codec&&\"AV1X\"!==i.codec&&\"AV1\"!==i.codec||(s.codecType=i.codec),s.sendBytes=i.bytes,s.sendBitrate=t?8*Math.max(0,s.sendBytes-t.sendBytes):0,i.inputFrame?(s.captureFrameRate=i.inputFrame.frameRate,s.captureResolutionHeight=i.inputFrame.height,s.captureResolutionWidth=i.inputFrame.width):n&&(s.captureResolutionWidth=n.width,s.captureResolutionHeight=n.height),i.sentFrame?(s.sendFrameRate=i.sentFrame.frameRate,s.sendResolutionHeight=i.sentFrame.height,s.sendResolutionWidth=i.sentFrame.width):n&&(s.sendResolutionWidth=n.width,s.sendResolutionHeight=n.height),i.avgEncodeMs&&(s.encodeDelay=i.avgEncodeMs),r&&r.bitrateMax&&(s.targetSendBitrate=1e3*r.bitrateMax),s.sendPackets=i.packets,s.sendPacketsLost=i.packetsLost,s.sendJitterMs=i.jitterMs,s.sendRttMs=i.rttMs,s.totalDuration=t?t.totalDuration+1:1,s.totalFreezeTime=t?t.totalFreezeTime:0,this.isLocalVideoFreeze(i)&&(s.totalFreezeTime+=1),i.scalabilityMode&&this.scalabilityMode!==i.scalabilityMode&&(jC.debug(\"[\".concat(this.store.clientId,\"]: The scalabilityMode of the video sending stream is \").concat(i.scalabilityMode)),this.scalabilityMode=i.scalabilityMode)}this.trafficStats&&(s.currentPacketLossRate=(this.trafficStats.B_pvlr4||0)/100)}var r;if(this.localStats.set(i,s),(null==t?void 0:t.sendResolutionWidth)!==s.sendResolutionWidth||(null==t?void 0:t.sendResolutionHeight)!==s.sendResolutionHeight)null===(r=this.onStatsChanged)||void 0===r||r.call(this,\"resolution\",{width:s.sendResolutionWidth,height:s.sendResolutionHeight});s&&a&&this.exceptionMonitor.setLocalVideoStats(this.store.uid,a.track,s);break}case lv.LocalAudioTrack:{const t=n,r=EV({},XA),s=e.getStats(),o=e.getLocalMedia(i);if(s){const i=s.audioSend.find((e=>e.ssrc===(null==o?void 0:o.ssrcs[0].ssrcId)));if(i){if(\"opus\"!==i.codec&&\"aac\"!==i.codec&&\"PCMU\"!==i.codec&&\"PCMA\"!==i.codec&&\"G722\"!==i.codec||(r.codecType=i.codec),i.inputLevel)r.sendVolumeLevel=Math.round(32767*i.inputLevel);else{const t=e.getLocalAudioVolume();t&&(r.sendVolumeLevel=Math.round(32767*t))}r.sendBytes=i.bytes,r.sendPackets=i.packets,r.sendPacketsLost=i.packetsLost,r.sendJitterMs=i.jitterMs,r.sendRttMs=i.rttMs,r.sendBitrate=t?8*Math.max(0,r.sendBytes-t.sendBytes):0}}this.trafficStats&&(r.currentPacketLossRate=(this.trafficStats.B_palr4||0)/100),this.localStats.set(lv.LocalAudioTrack,r),r&&o&&this.exceptionMonitor.setLocalAudioStats(this.store.uid,o.track,r);break}}}))}updateRemoteStats(e){Array.from(this.remoteStats.entries()).forEach((t=>{var i,n;let[r,{videoStats:s,audioStats:o,videoPcStats:a}]=t;const c=o,d=s,l=a,u=EV({},ZA),h=EV({},eb),p=EV({},$A),{audioTrack:_,videoTrack:E,audioSSRC:m,videoSSRC:f}=e.getRemoteMedia(r);let g;g=e instanceof hV?e.getStats(!0):e.getStats();const T=null===(i=g)||void 0===i?void 0:i.audioRecv.find((e=>e.ssrc===m)),S=null===(n=g)||void 0===n?void 0:n.videoRecv.find((e=>e.ssrc===f)),R=this.trafficStats&&this.trafficStats.peer_delay.find((e=>e.peer_uid===r));if(T&&(\"opus\"!==T.codec&&\"aac\"!==T.codec&&\"PCMU\"!==T.codec&&\"PCMA\"!==T.codec&&\"G722\"!==T.codec||(u.codecType=T.codec),T.outputLevel?u.receiveLevel=Math.round(32767*T.outputLevel):_&&(u.receiveLevel=Math.round(32767*_.getVolumeLevel())),u.receiveBytes=T.bytes,u.receivePackets=T.packets,u.receivePacketsLost=T.packetsLost,u.packetLossRate=u.receivePacketsLost/(u.receivePackets+u.receivePacketsLost),u.receiveBitrate=c?8*Math.max(0,u.receiveBytes-c.receiveBytes):0,u.totalDuration=c?c.totalDuration+1:1,u.totalFreezeTime=c?c.totalFreezeTime:0,u.freezeRate=u.totalFreezeTime/u.totalDuration,u.receiveDelay=T.jitterBufferMs,u.totalDuration>10&&mV.isRemoteAudioFreeze(_)&&(u.totalFreezeTime+=1)),S){\"H264\"!==S.codec&&\"H265\"!==S.codec&&\"VP8\"!==S.codec&&\"VP9\"!==S.codec&&\"AV1X\"!==S.codec&&\"AV1\"!==S.codec||(h.codecType=S.codec),h.receiveBytes=S.bytes,h.receiveBitrate=d?8*Math.max(0,h.receiveBytes-d.receiveBytes):0,h.decodeFrameRate=S.decodeFrameRate<0?0:S.decodeFrameRate,h.renderFrameRate=S.decodeFrameRate<0?0:S.decodeFrameRate,S.outputFrame&&(h.renderFrameRate=S.outputFrame.frameRate),S.receivedFrame?(h.receiveFrameRate=S.receivedFrame.frameRate,h.receiveResolutionHeight=S.receivedFrame.height,h.receiveResolutionWidth=S.receivedFrame.width):E&&(h.receiveResolutionHeight=E._videoHeight||0,h.receiveResolutionWidth=E._videoWidth||0),void 0!==S.framesRateFirefox&&(h.receiveFrameRate=Math.round(S.framesRateFirefox)),h.receivePackets=S.packets,h.receivePacketsLost=S.packetsLost,h.packetLossRate=h.receivePacketsLost/(h.receivePackets+h.receivePacketsLost),h.totalDuration=d?d.totalDuration+1:1,h.totalFreezeTime=d?d.totalFreezeTime:0,h.receiveDelay=S.jitterBufferMs||0;const t=!!f&&e.getRemoteVideoIsReady(f);E&&t&&mV.isRemoteVideoFreeze(E,S,l)&&(h.totalFreezeTime+=1),h.freezeRate=h.totalFreezeTime/h.totalDuration}R&&(u.end2EndDelay=R.B_ad,h.end2EndDelay=R.B_vd,u.transportDelay=R.B_ed,h.transportDelay=R.B_ed,u.currentPacketLossRate=R.B_ealr4/100,h.currentPacketLossRate=R.B_evlr4/100,p.uplinkNetworkQuality=R.B_punq?R.B_punq:0,p.downlinkNetworkQuality=R.B_pdnq?R.B_pdnq:0),this.remoteStats.set(r,{audioStats:u,videoStats:h,videoPcStats:S,networkStats:p}),_&&this.exceptionMonitor.setRemoteAudioStats(_,u),E&&this.exceptionMonitor.setRemoteVideoStats(E,h)}))}}function fV(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function gV(e){for(var t=1;t{this.reconnectMode=\"retry\",this.startPingPong()})),sh(this,\"handleWebSocketMessage\",(e=>{if(!e.data)return;const t=JSON.parse(e.data);t.requestId?this.emit(\"@\".concat(t.requestId,\"-\").concat(t.sid),t):this.serviceMode===RI.INJECT?this.emit(jI.INJECT_STREAM_STATUS,t):(eI.workerEvent(this.spec.sid,{actionType:\"status\",serverCode:t.code,workerType:this.serviceMode===RI.TRANSCODE?1:2}),this.emit(jI.PUBLISH_STREAM_STATUS,t))})),this.spec=t,this.token=e,this.serviceMode=n,this.websocket=new zv(\"live-streaming\",i),this.websocket.on(SI.CONNECTED,this.handleWebSocketOpen),this.websocket.on(SI.ON_MESSAGE,this.handleWebSocketMessage),this.websocket.on(SI.REQUEST_NEW_URLS,((e,t)=>{vT(this,jI.REQUEST_NEW_ADDRESS).then(e).catch(t)})),this.websocket.on(SI.RECONNECTING,(()=>{this.websocket.reconnectMode=this.reconnectMode}))}init(e){return this.websocket.init(e)}async request(e,t,i,n){this.reqId+=1,\"request\"===e&&(this.commandReqId+=1);const r=this.commandReqId,s=this.reqId;if(!s||!this.websocket)throw new LI(Hg.UNEXPECTED_ERROR);const o=gV({command:e,sdkVersion:\"4.20.2\"===EC?\"0.0.1\":EC,seq:s,requestId:s,allocate:i,cname:this.spec.cname,appId:this.spec.appId,sid:this.spec.sid,uid:this.spec.uid.toString(),ts:Math.floor(Date.now()/1e3)},t);if(\"closed\"===this.websocket.state)throw new LI(Hg.WS_DISCONNECT);const a=()=>new cg(((e,t)=>{this.websocket.once(SI.CLOSED,(()=>t(new LI(Hg.WS_ABORT)))),this.websocket.once(SI.CONNECTED,e)}));\"connected\"!==this.websocket.state&&await a(),o.clientRequest&&(o.clientRequest.workerToken=this.token);const c=new cg(((e,t)=>{const i=()=>{t(new LI(Hg.WS_ABORT))};this.websocket.once(SI.RECONNECTING,i),this.websocket.once(SI.CLOSED,i),this.once(\"@\".concat(s,\"-\").concat(this.spec.sid),(t=>{e(t)}))}));n&&eI.workerEvent(this.spec.sid,gV(gV({},n),{},{requestId:r,actionType:\"request\",payload:JSON.stringify(t.clientRequest),serverCode:0,code:0}));const d=Date.now();this.websocket.sendMessage(o);let l=null;try{l=await c}catch(n){if(\"closed\"===this.websocket.state)throw n;return await a(),await this.request(e,t,i)}return n&&eI.workerEvent(this.spec.sid,gV(gV({},n),{},{requestId:r,actionType:\"response\",payload:JSON.stringify(l.serverResponse),serverCode:l.code,success:200===l.code,responseTime:Date.now()-d})),200!==l.code&&this.handleResponseError(l),l}tryNextAddress(){this.reconnectMode=\"tryNext\",this.websocket.reconnect(\"tryNext\")}close(){const e=\"4.20.2\"===EC?\"0.0.1\":EC;this.reqId+=1,\"connected\"===this.websocket.state?(this.websocket.sendMessage({command:\"request\",appId:this.spec.appId,cname:this.spec.cname,uid:this.spec.uid.toString(),sdkVersion:e,sid:this.spec.sid,seq:this.reqId,ts:Math.floor(Date.now()/1e3),requestId:this.reqId,clientRequest:{command:\"DestroyWorker\"}}),this.websocket.close(!1,!0)):this.websocket.close(!1),this.pingpongTimer&&(window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0)}handleResponseError(e){switch(e.code){case WI.LIVE_STREAM_RESPONSE_ALREADY_EXISTS_STREAM:return void jC.warning(\"live stream response already exists stream\");case WI.LIVE_STREAM_RESPONSE_TRANSCODING_PARAMETER_ERROR:case WI.LIVE_STREAM_RESPONSE_BAD_STREAM:case WI.LIVE_STREAM_RESPONSE_WM_PARAMETER_ERROR:return new LI(Hg.LIVE_STREAMING_INVALID_ARGUMENT,\"\",{code:e.code}).throw();case WI.LIVE_STREAM_RESPONSE_WM_WORKER_NOT_EXIST:if(\"UnpublishStream\"===e.serverResponse.command||\"UninjectStream\"===e.serverResponse.command)return;throw new LI(Hg.LIVE_STREAMING_INTERNAL_SERVER_ERROR,\"live stream response wm worker not exist\",{retry:!0});case WI.LIVE_STREAM_RESPONSE_NOT_AUTHORIZED:return new LI(Hg.LIVE_STREAMING_PUBLISH_STREAM_NOT_AUTHORIZED,\"\",{code:e.code}).throw();case WI.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE:{const t=new LI(Hg.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE);return this.emit(jI.WARNING,t,e.serverResponse.url)}case WI.LIVE_STREAM_RESPONSE_REQUEST_TOO_OFTEN:{const t=new LI(Hg.LIVE_STREAMING_WARN_FREQUENT_REQUEST);return this.emit(jI.WARNING,t,e.serverResponse.url)}case WI.LIVE_STREAM_RESPONSE_NOT_FOUND_PUBLISH:throw new LI(Hg.LIVE_STREAMING_INTERNAL_SERVER_ERROR,\"live stream response wm worker not exist\",{retry:!0});case WI.LIVE_STREAM_RESPONSE_NOT_SUPPORTED:return new LI(Hg.LIVE_STREAMING_TRANSCODING_NOT_SUPPORTED,\"\",{code:e.code}).throw();case WI.LIVE_STREAM_RESPONSE_MAX_STREAM_NUM:{const t=new LI(Hg.LIVE_STREAMING_WARN_STREAM_NUM_REACH_LIMIT);return this.emit(jI.WARNING,t,e.serverResponse.url)}case WI.LIVE_STREAM_RESPONSE_INTERNAL_SERVER_ERROR:return new LI(Hg.LIVE_STREAMING_INTERNAL_SERVER_ERROR,\"\",{code:e.code}).throw();case WI.LIVE_STREAM_RESPONSE_RESOURCE_LIMIT:throw new LI(Hg.LIVE_STREAMING_INTERNAL_SERVER_ERROR,\"live stream resource limit\",{retry:!0,changeAddress:!0});case WI.LIVE_STREAM_RESPONSE_WORKER_LOST:case WI.LIVE_STREAM_RESPONSE_WORKER_QUIT:if(\"UnpublishStream\"===e.serverResponse.command||\"UninjectStream\"===e.serverResponse.command)return;throw new LI(Hg.LIVE_STREAMING_INTERNAL_SERVER_ERROR,\"error fail send message\",{retry:!0,changeAddress:!0});case WI.ERROR_FAIL_SEND_MESSAGE:if(\"UnpublishStream\"===e.serverResponse.command||\"UninjectStream\"===e.serverResponse.command)return;if(\"UpdateTranscoding\"===e.serverResponse.command||\"ControlStream\"===e.serverResponse.command)return new LI(Hg.LIVE_STREAMING_INTERNAL_SERVER_ERROR,\"error fail send message\",{code:e.code}).throw();throw new LI(Hg.LIVE_STREAMING_INTERNAL_SERVER_ERROR,\"error fail send message\",{retry:!0,changeAddress:!0});case WI.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN:case WI.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT:case WI.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE:case WI.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH:return new LI(Hg.LIVE_STREAMING_CDN_ERROR,\"\",{code:e.code}).throw()}}startPingPong(){this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval((()=>{\"connected\"===this.websocket.state&&this.request(\"ping\",{}).catch(sS)}),6e3)}}function SV(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function RV(e){for(var t=1;t1&&void 0!==arguments[1]?arguments[1]:ES,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:ES;super(),sh(this,\"onLiveStreamWarning\",void 0),sh(this,\"onLiveStreamError\",void 0),sh(this,\"onInjectStatusChange\",void 0),sh(this,\"spec\",void 0),sh(this,\"retryTimeout\",1e4),sh(this,\"connection\",void 0),sh(this,\"httpRetryConfig\",void 0),sh(this,\"wsRetryConfig\",void 0),sh(this,\"streamingTasks\",new Map),sh(this,\"isStartingStreamingTask\",!1),sh(this,\"taskMutex\",new pS(\"live-streaming\")),sh(this,\"cancelToken\",sC.CancelToken.source()),sh(this,\"transcodingConfig\",void 0),sh(this,\"injectConfig\",RV({},BI)),sh(this,\"injectLoopTimes\",0),sh(this,\"uapResponse\",void 0),sh(this,\"lastTaskId\",1),sh(this,\"statusError\",new Map),this.spec=e,this.httpRetryConfig=i,this.wsRetryConfig=t}async setTranscodingConfig(e){const t=RV(RV({},FI),e);66!==t.videoCodecProfile&&77!==t.videoCodecProfile&&100!==t.videoCodecProfile&&(jC.debug(\"[\".concat(this.spec.clientId,\"] set transcoding config, fix video codec profile: \").concat(t.videoCodecProfile,\" -> 100\")),t.videoCodecProfile=100),t.transcodingUsers||(t.transcodingUsers=t.userConfigs),t.transcodingUsers&&(t.transcodingUsers=t.transcodingUsers.map((e=>RV(RV(RV({},UI),e),{},{zOrder:e.zOrder?e.zOrder+1:1})))),function(e){Zg(e.width)||zg(e.width,\"config.width\",0,1e4),Zg(e.height)||zg(e.height,\"config.height\",0,1e4),Zg(e.videoBitrate)||zg(e.videoBitrate,\"config.videoBitrate\",1,1e6),Zg(e.videoFrameRate)||zg(e.videoFrameRate,\"config.videoFrameRate\"),Zg(e.lowLatency)||Yg(e.lowLatency,\"config.lowLatency\"),Zg(e.audioSampleRate)||qg(e.audioSampleRate,\"config.audioSampleRate\",[32e3,44100,48e3]),Zg(e.audioBitrate)||zg(e.audioBitrate,\"config.audioBitrate\",1,128),Zg(e.audioChannels)||qg(e.audioChannels,\"config.audioChannels\",[1,2,3,4,5]),Zg(e.videoGop)||zg(e.videoGop,\"config.videoGop\"),Zg(e.videoCodecProfile)||qg(e.videoCodecProfile,\"config.videoCodecProfile\",[66,77,100]),Zg(e.userCount)||zg(e.userCount,\"config.userCount\",0,17),Zg(e.backgroundColor)||zg(e.backgroundColor,\"config.backgroundColor\",0,16777215),Zg(e.userConfigExtraInfo)||Xg(e.userConfigExtraInfo,\"config.userConfigExtraInfo\",0,4096,!1),e.transcodingUsers&&!Zg(e.transcodingUsers)&&(Qg(e.transcodingUsers,\"config.transcodingUsers\"),e.transcodingUsers.forEach(((e,t)=>{MI(e.uid),Zg(e.x)||zg(e.x,\"transcodingUser[\".concat(t,\"].x\"),0,1e4),Zg(e.y)||zg(e.y,\"transcodingUser[\".concat(t,\"].y\"),0,1e4),Zg(e.width)||zg(e.width,\"transcodingUser[\".concat(t,\"].width\"),0,1e4),Zg(e.height)||zg(e.height,\"transcodingUser[\".concat(t,\"].height\"),0,1e4),Zg(e.zOrder)||zg(e.zOrder-1,\"transcodingUser[\".concat(t,\"].zOrder\"),0,100),Zg(e.alpha)||zg(e.alpha,\"transcodingUser[\".concat(t,\"].alpha\"),0,1,!1)}))),Zg(e.watermark)||VI(e.watermark,\"watermark\"),Zg(e.backgroundImage)||VI(e.backgroundImage,\"backgroundImage\"),e.images&&!Zg(e.images)&&(Qg(e.images,\"config.images\"),e.images.forEach(((e,t)=>{VI(e,\"images[\".concat(t,\"]\"))})))}(t);const i=[];t.images&&i.push(...t.images.map((e=>RV(RV(RV({},xI),e),{},{zOrder:255})))),t.backgroundImage&&(i.push(RV(RV(RV({},xI),t.backgroundImage),{},{zOrder:0})),delete t.backgroundImage),t.watermark&&(i.push(RV(RV(RV({},xI),t.watermark),{},{zOrder:255})),delete t.watermark),t.images=i,t.transcodingUsers&&(t.userConfigs=t.transcodingUsers.map((e=>RV({},e))),t.userCount=t.transcodingUsers.length,delete t.transcodingUsers);const n=(t.userConfigs||[]).map((e=>\"number\"==typeof e.uid?cg.resolve(e.uid):pA(e.uid,this.spec,this.cancelToken.token,this.httpRetryConfig)));if((await cg.all(n)).forEach(((e,i)=>{t.userConfigs&&t.userConfigs[i]&&(t.userConfigs[i].uid=e)})),this.transcodingConfig=t,this.connection)try{var r;const e=await this.connection.request(\"request\",{clientRequest:{command:\"UpdateTranscoding\",transcodingConfig:this.transcodingConfig}},!1,{command:\"UpdateTranscoding\",workerType:1,requestByUser:!0,tid:Array.from(NI(r=this.streamingTasks).call(r)).map((e=>e.taskId)).join(\"#\")});jC.debug(\"[\".concat(this.spec.clientId,\"] update live transcoding config success, code: \").concat(e.code,\", config:\"),JSON.stringify(this.transcodingConfig))}catch(e){if(!e.data||!e.data.retry)throw e;e.data.changeAddress&&this.connection.tryNextAddress(),this.streamingTasks.forEach((t=>{jC.warning(\"[\".concat(this.spec.clientId,\"] live streaming receive error\"),e.toString(),\"try to republish\",t.url),this.startLiveStreamingTask(t.url,t.mode,e).then((()=>{jC.debug(\"[\".concat(this.spec.clientId,\"] live streaming republish \").concat(t.url,\" success\"))})).catch((e=>{jC.error(\"[\".concat(this.spec.clientId,\"] live streaming republish failed\"),t.url,e.toString()),this.onLiveStreamError&&this.onLiveStreamError(t.url,e)}))}))}}setInjectStreamConfig(e,t){this.injectConfig=Object.assign({},this.injectConfig,e),this.injectLoopTimes=t}async startLiveStreamingTask(e,t,i){var n;if(Array.from(NI(n=this.streamingTasks).call(n)).find((e=>e.mode===RI.INJECT))&&t===RI.INJECT)return new LI(Hg.LIVE_STREAMING_TASK_CONFLICT,\"inject stream over limit\").throw();if(!this.transcodingConfig&&t===RI.TRANSCODE)throw new LI(Hg.INVALID_OPERATION,\"[LiveStreaming] no transcoding config found, can not start transcoding streaming task\");let r={command:\"PublishStream\",ts:Date.now(),url:e,uid:this.spec.uid.toString(),autoDestroyTime:100,acceptImageTimeout:!0};jC.debug(\"[\".concat(this.spec.clientId,\"] start live streaming \").concat(e,\", mode: \").concat(t));const s=await this.taskMutex.lock();if(!this.connection&&i)return void s();if(this.streamingTasks.get(e)&&!i)return s(),new LI(Hg.LIVE_STREAMING_TASK_CONFLICT).throw();try{this.connection||(this.connection=await this.connect(t))}catch(e){throw s(),e}switch(t){case RI.TRANSCODE:r.transcodingConfig=RV({},this.transcodingConfig);break;case RI.RAW:break;case RI.INJECT:r={cname:this.spec.cname,command:\"InjectStream\",sid:this.spec.sid,transcodingConfig:this.injectConfig,ts:Date.now(),url:e,loopTimes:this.injectLoopTimes}}this.uapResponse&&this.uapResponse.vid&&(r.vid=this.uapResponse.vid),this.isStartingStreamingTask=!0;const o=this.lastTaskId++;try{const n=new cg(((t,n)=>{iS(this.retryTimeout).then((()=>{if(i)return n(i);const t=this.statusError.get(e);return t?(this.statusError.delete(e),n(t)):void 0}))})),a=await cg.race([this.connection.request(\"request\",{clientRequest:r},!0,{url:e,command:\"PublishStream\",workerType:t===RI.TRANSCODE?1:2,requestByUser:!i,tid:o.toString()}),n]);this.isStartingStreamingTask=!1,jC.debug(\"[\".concat(this.spec.clientId,\"] live streaming started, code: \").concat(a.code)),this.streamingTasks.set(e,{clientRequest:r,mode:t,url:e,taskId:o}),s()}catch(n){if(s(),this.isStartingStreamingTask=!1,!n.data||!n.data.retry||i)throw n;return n.data.changeAddress?(this.connection.tryNextAddress(),await this.startLiveStreamingTask(e,t,n)):await this.startLiveStreamingTask(e,t,n)}}stopLiveStreamingTask(e){return new cg(((t,i)=>{const n=this.streamingTasks.get(e);if(!n||!this.connection)return new LI(Hg.UNEXPECTED_ERROR,\"can not find streaming task to stop\").throw();const r=n.mode;n.abortTask=()=>{jC.debug(\"[\".concat(this.spec.clientId,\"] stop live streaming success(worker exception)\")),this.streamingTasks.delete(e),t()},this.connection.request(\"request\",{clientRequest:{command:r===RI.INJECT?\"UninjectStream\":\"UnpublishStream\",url:n.url}},!1,{url:e,command:\"UnPublishStream\",workerType:r===RI.TRANSCODE?1:2,requestByUser:!0,tid:(this.lastTaskId++).toString()}).then((i=>{jC.debug(\"[\".concat(this.spec.clientId,\"] stop live streaming success, code: \").concat(i.code)),this.streamingTasks.delete(e),0===this.streamingTasks.size&&r!==RI.INJECT&&(this.connection&&this.connection.close(),this.connection=void 0),t(),r===RI.INJECT&&this.onInjectStatusChange&&this.onInjectStatusChange(CI.INJECT_STREAM_STATUS_STOP_SUCCESS,this.spec.uid,e)})).catch(i)}))}async controlInjectStream(e,t,i,n){const r=this.streamingTasks.get(e);if(!r||!this.connection||r.mode!==RI.INJECT)throw new LI(Hg.INVALID_OPERATION,\"can not find inject stream task to control\");return(await this.connection.request(\"request\",{clientRequest:{command:\"ControlStream\",url:e,control:t,audioVolume:i,position:n}})).serverResponse}resetAllTask(){var e;const t=Array.from(NI(e=this.streamingTasks).call(e));this.terminate();for(const e of t)this.startLiveStreamingTask(e.url,e.mode).catch((t=>{this.onLiveStreamError&&this.onLiveStreamError(e.url,t)}))}terminate(){this.cancelToken&&this.cancelToken.cancel(),this.streamingTasks=new Map,this.isStartingStreamingTask=!1,this.statusError=new Map,this.cancelToken=sC.CancelToken.source(),this.uapResponse=void 0,this.connection&&this.connection.close(),this.connection=void 0}async connect(e){if(this.connection)throw new LI(Hg.UNEXPECTED_ERROR,\"live streaming connection has already connected\");const t=await vT(this,GI.REQUEST_WORKER_MANAGER_LIST,e);return this.uapResponse=t,this.connection=new TV(t.workerToken,this.spec,this.wsRetryConfig,e),this.connection.on(jI.WARNING,((e,t)=>this.onLiveStreamWarning&&this.onLiveStreamWarning(t,e))),this.connection.on(jI.PUBLISH_STREAM_STATUS,(e=>this.handlePublishStreamServer(e))),this.connection.on(jI.INJECT_STREAM_STATUS,(e=>this.handleInjectStreamServerStatus(e))),this.connection.on(jI.REQUEST_NEW_ADDRESS,((t,i)=>{if(!this.connection)return i(new LI(Hg.UNEXPECTED_ERROR,\"can not get new live streaming address list\"));vT(this,GI.REQUEST_WORKER_MANAGER_LIST,e).then((e=>{this.uapResponse=e,t(e.addressList)})).catch(i)})),await this.connection.init(t.addressList),this.connection}handlePublishStreamServer(e){const t=e.serverStatus&&e.serverStatus.url||\"empty_url\",i=this.streamingTasks.get(t),n=e.reason;switch(e.code){case WI.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN:case WI.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT:case WI.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE:case WI.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH:{const n=new LI(Hg.LIVE_STREAMING_CDN_ERROR,\"\",{code:e.code});if(i)return jC.error(n.toString()),this.onLiveStreamError&&this.onLiveStreamError(t,n);if(!this.isStartingStreamingTask)return;this.statusError.set(t,n)}case WI.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE:{const e=new LI(Hg.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE,n);return this.onLiveStreamWarning&&this.onLiveStreamWarning(t,e)}case WI.LIVE_STREAM_RESPONSE_WORKER_LOST:case WI.LIVE_STREAM_RESPONSE_WORKER_QUIT:{var r;if(!this.connection)return;this.connection.tryNextAddress();const t=Array.from(NI(r=this.streamingTasks).call(r));for(const i of t)i.abortTask?i.abortTask():(jC.warning(\"[\".concat(this.spec.clientId,\"] publish stream status code\"),e.code,\"try to republish\",i.url),this.startLiveStreamingTask(i.url,i.mode,new LI(Hg.LIVE_STREAMING_INTERNAL_SERVER_ERROR,\"\",{code:e.code})).then((()=>{jC.debug(\"[\".concat(this.spec.clientId,\"] republish live stream success\"),i.url)})).catch((e=>{jC.error(e.toString()),this.onLiveStreamError&&this.onLiveStreamError(i.url,e)})));return}}}handleInjectStreamServerStatus(e){const t=Number(e.uid),i=e.serverStatus&&e.serverStatus.url;switch(e.code){case 200:return void(this.onInjectStatusChange&&this.onInjectStatusChange(CI.INJECT_STREAM_STATUS_START_SUCCESS,t,i));case 451:return this.onInjectStatusChange&&this.onInjectStatusChange(CI.INJECT_STREAM_STATUS_START_ALREADY_EXISTS,t,i),void this.streamingTasks.delete(i);case 453:return this.onInjectStatusChange&&this.onInjectStatusChange(CI.INJECT_STREAM_STATUS_START_UNAUTHORIZED,t,i),void this.streamingTasks.delete(i);case 470:return this.onInjectStatusChange&&this.onInjectStatusChange(CI.INJECT_STREAM_STATUS_BROKEN,t,i),void this.streamingTasks.delete(i);case 499:return this.onInjectStatusChange&&this.onInjectStatusChange(CI.INJECT_STREAM_STATUS_START_TIMEOUT,t,i),void this.streamingTasks.delete(i);default:return void jC.debug(\"inject stream server status\",e)}}hasUrl(e){return this.streamingTasks.has(e)}}class IV{constructor(){sh(this,\"destChannelMediaInfos\",new Map),sh(this,\"srcChannelMediaInfo\",void 0)}setSrcChannelInfo(e){tv(e),this.srcChannelMediaInfo=e}addDestChannelInfo(e){tv(e),this.destChannelMediaInfos.set(e.channelName,e)}removeDestChannelInfo(e){kI(e),this.destChannelMediaInfos.delete(e)}getSrcChannelMediaInfo(){return this.srcChannelMediaInfo}getDestChannelMediaInfo(){return this.destChannelMediaInfos}}function vV(e){if(!(e instanceof IV)){return new LI(Hg.INVALID_PARAMS,\"Config should be instance of [ChannelMediaRelayConfiguration]\").throw()}const t=e.getSrcChannelMediaInfo(),i=e.getDestChannelMediaInfo();if(!t){return new LI(Hg.INVALID_PARAMS,\"srcChannelMediaInfo should not be empty\").throw()}if(0===i.size){return new LI(Hg.INVALID_PARAMS,\"destChannelMediaInfo should not be empty\").throw()}}class yV extends dT{constructor(e,t,i){super(),sh(this,\"ws\",void 0),sh(this,\"requestId\",1),sh(this,\"heartBeatTimer\",void 0),sh(this,\"joinInfo\",void 0),sh(this,\"clientId\",void 0),sh(this,\"onOpen\",(()=>{this.emit(\"open\"),this.startHeartBeatCheck()})),sh(this,\"onClose\",(e=>{this.emit(\"close\"),this.dispose()})),sh(this,\"onMessage\",(e=>{const t=JSON.parse(e.data);if(!t||\"serverResponse\"!==t.command||!t.requestId)return t&&\"serverStatus\"===t.command&&t.serverStatus&&t.serverStatus.command?(this.emit(\"status\",t.serverStatus),void this.emit(t.serverStatus.command,t.serverStatus)):void 0;this.emit(\"req_\".concat(t.requestId),t)})),this.joinInfo=e,this.clientId=t,this.ws=new zv(\"cross-channel-\".concat(this.clientId),i),this.ws.on(SI.RECONNECTING,(()=>{this.ws.reconnectMode=\"retry\",this.emit(\"reconnecting\")})),this.ws.on(SI.CONNECTED,this.onOpen),this.ws.on(SI.ON_MESSAGE,this.onMessage),this.ws.on(SI.CLOSED,this.onClose)}isConnect(){return\"connected\"===this.ws.state}sendMessage(e){const t=this.requestId++;return e.requestId=t,e.seq=t,this.ws.sendMessage(e),t}waitStatus(e){return new cg(((t,i)=>{const n=window.setTimeout((()=>{i(new LI(Hg.TIMEOUT,\"wait status timeout, status: \".concat(e)))}),5e3);this.once(e,(r=>{window.clearTimeout(n),r.state&&0!==r.state?i(new LI(Hg.CROSS_CHANNEL_WAIT_STATUS_ERROR,\"wait status error, status: \".concat(e))):t(void 0)})),this.once(\"dispose\",(()=>{window.clearTimeout(n),i(new LI(Hg.WS_ABORT))}))}))}async request(e){if(\"closed\"===this.ws.state)throw new LI(Hg.WS_DISCONNECT);const t=()=>new cg(((e,t)=>{this.ws.once(SI.CLOSED,(()=>t(new LI(Hg.WS_ABORT)))),this.ws.once(SI.CONNECTED,e)}));\"connected\"!==this.ws.state&&await t();const i=this.sendMessage(e),n=new cg(((e,t)=>{const n=()=>{t(new LI(Hg.WS_ABORT))};this.ws.once(SI.RECONNECTING,n),this.ws.once(SI.CLOSED,n),this.once(\"req_\".concat(i),e),iS(3e3).then((()=>{this.removeAllListeners(\"req_\".concat(i)),this.ws.off(SI.RECONNECTING,n),this.ws.off(SI.CLOSED,n),t(new LI(Hg.TIMEOUT,\"cross channel ws request timeout\"))}))})),r=await n;if(!r||200!==r.code)throw new LI(Hg.CROSS_CHANNEL_SERVER_ERROR_RESPONSE,\"response: \".concat(JSON.stringify(r)));return r}async connect(e){this.ws.removeAllListeners(SI.REQUEST_NEW_URLS),this.ws.on(SI.REQUEST_NEW_URLS,(t=>{t(e)})),await this.ws.init(e)}dispose(){this.clearHeartBeatCheck(),this.emit(\"dispose\"),this.removeAllListeners(),this.ws.close()}sendPing(e){const t=this.requestId++;return e.requestId=t,this.ws.sendMessage(e),t}startHeartBeatCheck(){this.heartBeatTimer&&window.clearInterval(this.heartBeatTimer),this.heartBeatTimer=window.setInterval((()=>{this.sendPing({command:\"ping\",appId:this.joinInfo.appId,cname:this.joinInfo.cname,uid:this.joinInfo.uid.toString(),sid:this.joinInfo.sid,ts:+new Date,requestId:0})}),3e3)}clearHeartBeatCheck(){window.clearInterval(this.heartBeatTimer),this.heartBeatTimer=void 0}}class AV extends dT{set state(e){e!==this._state&&(e!==qI.RELAY_STATE_FAILURE&&(this.errorCode=zI.RELAY_OK),this.emit(\"state\",e,this.errorCode),this._state=e)}get state(){return this._state}constructor(e,t,i,n,r){super(),sh(this,\"joinInfo\",void 0),sh(this,\"sid\",void 0),sh(this,\"clientId\",void 0),sh(this,\"cancelToken\",sC.CancelToken.source()),sh(this,\"workerToken\",void 0),sh(this,\"requestId\",0),sh(this,\"signal\",void 0),sh(this,\"prevChannelMediaConfig\",void 0),sh(this,\"httpRetryConfig\",void 0),sh(this,\"_resolution\",void 0),sh(this,\"_state\",qI.RELAY_STATE_IDLE),sh(this,\"errorCode\",zI.RELAY_OK),sh(this,\"onStatus\",(e=>{jC.debug(\"[\".concat(this.clientId,\"] ChannelMediaStatus: \").concat(JSON.stringify(e))),e&&e.command&&(\"onAudioPacketReceived\"===e.command&&this.emit(\"event\",YI.PACKET_RECEIVED_AUDIO_FROM_SRC),\"onVideoPacketReceived\"===e.command&&this.emit(\"event\",YI.PACKET_RECEIVED_VIDEO_FROM_SRC),\"onSrcTokenPrivilegeDidExpire\"===e.command&&(this.errorCode=zI.SRC_TOKEN_EXPIRED,this.state=qI.RELAY_STATE_FAILURE),\"onDestTokenPrivilegeDidExpire\"===e.command&&(this.errorCode=zI.DEST_TOKEN_EXPIRED,this.state=qI.RELAY_STATE_FAILURE))})),sh(this,\"onReconnect\",(async()=>{jC.debug(\"[\".concat(this.clientId,\"] ChannelMediaSocket disconnect, reconnecting\")),this.emit(\"event\",YI.NETWORK_DISCONNECTED),this.state=qI.RELAY_STATE_IDLE,this.prevChannelMediaConfig&&this.sendStartRelayMessage(this.prevChannelMediaConfig).catch((e=>{this.state!==qI.RELAY_STATE_IDLE&&(jC.error(\"auto restart channel media relay failed\",e.toString()),this.errorCode=zI.SERVER_CONNECTION_LOST,this.state=qI.RELAY_STATE_FAILURE)}))})),this.joinInfo=e,this.clientId=t,this.sid=rS(),this.signal=new yV(this.joinInfo,this.clientId,i),this.httpRetryConfig=n,this._resolution=r}async startChannelMediaRelay(e){if(this.state!==qI.RELAY_STATE_IDLE)throw new LI(Hg.INVALID_OPERATION);this.state=qI.RELAY_STATE_CONNECTING,await this.connect(),jC.debug(\"[\".concat(this.clientId,\"] startChannelMediaRelay: connect success\"));try{await this.sendStartRelayMessage(e)}catch(e){if(e.data&&e.data.serverResponse&&\"SetSourceChannel\"===e.data.serverResponse.command)throw new LI(Hg.CROSS_CHANNEL_FAILED_JOIN_SRC);if(e.data&&e.data.serverResponse&&\"SetDestChannelStatus\"===e.serverResponse.command)throw new LI(Hg.CROSS_CHANNEL_FAILED_JOIN_DEST);if(e.data&&e.data.serverResponse&&\"StartPacketTransfer\"===e.serverResponse.command)throw new LI(Hg.CROSS_CHANNEL_FAILED_PACKET_SENT_TO_DEST);throw e}this.prevChannelMediaConfig=e}async updateChannelMediaRelay(e){if(this.state!==qI.RELAY_STATE_RUNNING)throw new LI(Hg.INVALID_OPERATION);await this.sendUpdateMessage(e),this.prevChannelMediaConfig=e}async setVideoProfile(e){if(this._resolution=e,this.state!==qI.RELAY_STATE_RUNNING)throw new LI(Hg.INVALID_OPERATION);const t=this.genMessage(KI.SetVideoProfile);await this.signal.request(t),jC.debug(\"[\".concat(this.clientId,\"] startChannelMediaRelay: setVideoProfile success\"))}async stopChannelMediaRelay(){await this.sendStopRelayMessage(),jC.debug(\"[\".concat(this.clientId,\"] stopChannelMediaRelay: send stop message success\")),this.state=qI.RELAY_STATE_IDLE,this.dispose()}dispose(){jC.debug(\"[\".concat(this.clientId,\"] disposeChannelMediaRelay\")),this.cancelToken.cancel(),this.cancelToken=sC.CancelToken.source(),this.state=qI.RELAY_STATE_IDLE,this.emit(\"dispose\"),this.signal.dispose(),this.prevChannelMediaConfig=void 0}async connect(){const e=await fA(this.joinInfo,this.cancelToken.token,this.httpRetryConfig);this.workerToken=e.workerToken,await this.signal.connect(e.addressList),this.emit(\"event\",YI.NETWORK_CONNECTED),this.signal.on(\"status\",this.onStatus),this.signal.on(\"reconnecting\",this.onReconnect)}async sendStartRelayMessage(e){const t=this.genMessage(KI.StopPacketTransfer);await this.signal.request(t),await this.signal.waitStatus(\"Normal Quit\"),jC.debug(\"[\".concat(this.clientId,\"] startChannelMediaRelay: StopPacketTransfer success\"));const i=this.genMessage(KI.SetSdkProfile,e);await this.signal.request(i),jC.debug(\"[\".concat(this.clientId,\"] startChannelMediaRelay: SetSdkProfile success\"));const n=this.genMessage(KI.SetSourceChannel,e);await this.signal.request(n),await this.signal.waitStatus(\"SetSourceChannelStatus\"),this.emit(\"event\",YI.PACKET_JOINED_SRC_CHANNEL),jC.debug(\"[\".concat(this.clientId,\"] startChannelMediaRelay: SetSourceChannel success\"));const r=this.genMessage(KI.SetSourceUserId,e);await this.signal.request(r),jC.debug(\"[\".concat(this.clientId,\"] startChannelMediaRelay: SetSourceUserId success\"));const s=this.genMessage(KI.SetDestChannel,e);await this.signal.request(s),await this.signal.waitStatus(\"SetDestChannelStatus\"),this.emit(\"event\",YI.PACKET_JOINED_DEST_CHANNEL),jC.debug(\"[\".concat(this.clientId,\"] startChannelMediaRelay: SetDestChannel success\"));const o=this.genMessage(KI.StartPacketTransfer,e);await this.signal.request(o),this.emit(\"event\",YI.PACKET_SENT_TO_DEST_CHANNEL),this.state=qI.RELAY_STATE_RUNNING,jC.debug(\"[\".concat(this.clientId,\"] startChannelMediaRelay: StartPacketTransfer success\")),this.setVideoProfile(this._resolution)}async sendUpdateMessage(e){const t=this.genMessage(KI.UpdateDestChannel,e);await this.signal.request(t),this.emit(\"event\",YI.PACKET_UPDATE_DEST_CHANNEL),jC.debug(\"[\".concat(this.clientId,\"] sendUpdateMessage: UpdateDestChannel success\"))}async sendStopRelayMessage(){const e=this.genMessage(KI.StopPacketTransfer);await this.signal.request(e),jC.debug(\"[\".concat(this.clientId,\"] sendStopRelayMessage: StopPacketTransfer success\"))}genMessage(e,t){const i=[],n=[],r=[];this.requestId+=1;const s={appId:this.joinInfo.appId,cname:this.joinInfo.cname,uid:this.joinInfo.uid.toString(),sdkVersion:EC,sid:this.sid,ts:Date.now(),requestId:this.requestId,seq:this.requestId,allocate:!0,clientRequest:{}};\"4.20.2\"===s.sdkVersion&&(s.sdkVersion=\"0.0.1\");let o=null,a=null;switch(e){case KI.SetSdkProfile:return s.clientRequest={command:\"SetSdkProfile\",type:\"multi_channel\"},s;case KI.SetSourceChannel:if(a=t&&t.getSrcChannelMediaInfo(),!a)throw new LI(Hg.UNEXPECTED_ERROR,\"can not find source config\");return s.clientRequest={command:\"SetSourceChannel\",uid:\"0\",channelName:a.channelName,token:a.token||this.joinInfo.appId},s;case KI.SetSourceUserId:if(a=t&&t.getSrcChannelMediaInfo(),!a)throw new LI(Hg.UNEXPECTED_ERROR,\"can not find source config\");return s.clientRequest={command:\"SetSourceUserId\",uid:a.uid+\"\"},s;case KI.SetDestChannel:if(o=t&&t.getDestChannelMediaInfo(),!o)throw new LI(Hg.UNEXPECTED_ERROR,\"can not find dest config\");return o.forEach((e=>{i.push(e.channelName),n.push(e.uid+\"\"),r.push(e.token||this.joinInfo.appId)})),s.clientRequest={command:\"SetDestChannel\",channelName:i,uid:n,token:r},s;case KI.StartPacketTransfer:return s.clientRequest={command:\"StartPacketTransfer\"},s;case KI.Reconnect:return s.clientRequest={command:\"Reconnect\"},s;case KI.StopPacketTransfer:return s.clientRequest={command:\"StopPacketTransfer\"},s;case KI.UpdateDestChannel:if(o=t&&t.getDestChannelMediaInfo(),!o)throw new LI(Hg.UNEXPECTED_ERROR,\"can not find dest config\");return o.forEach((e=>{i.push(e.channelName),n.push(e.uid+\"\"),r.push(e.token||this.joinInfo.appId)})),s.clientRequest={command:\"UpdateDestChannel\",channelName:i,uid:n,token:r},s;case KI.SetVideoProfile:s.clientRequest={command:\"SetVideoProfile\",width:this._resolution.width,height:this._resolution.height}}return s}}function bV(e){var t={},i=!1;function n(t,n){return i=!0,{done:!1,value:new CU(n=new wU((function(i){i(e[t](n))})),1)}}return t[void 0!==xu&&th||\"@@iterator\"]=function(){return this},t.next=function(e){return i?(i=!1,e):n(\"next\",e)},\"function\"==typeof e.throw&&(t.throw=function(e){if(i)throw i=!1,e;return n(\"throw\",e)}),\"function\"==typeof e.return&&(t.return=function(e){return i?(i=!1,e):n(\"return\",e)}),t}var wV=i(OU);function OV(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function NV(e){for(var t=1;te.rtpMap&&e.rtpMap.encodingName.toLowerCase()||\"\")).filter((e=>{var t;return bn(t=Object.keys(bC)).call(t,e)})))]}constructor(e,t){super(e,t),sh(this,\"store\",void 0),sh(this,\"peerConnection\",void 0),sh(this,\"remoteSDP\",void 0),sh(this,\"initialOffer\",void 0),sh(this,\"statsFilter\",void 0),sh(this,\"useRTX\",!1),sh(this,\"localCapabilities\",void 0),sh(this,\"localCandidateCount\",0),sh(this,\"allCandidatesReceived\",!1),sh(this,\"establishPromise\",void 0),sh(this,\"mutex\",new pS(\"P2PConnection-mutex\")),this.store=t,this.peerConnection=new RTCPeerConnection(LV.resolvePCConfiguration(e),{optional:[{googDscp:!0}]}),this.statsFilter=Ex(this.peerConnection,RC(\"STATS_UPDATE_INTERVAL\"),void 0,wg()?1200:void 0),this.bindPCEvents(),this.bindStatsEvents(),this.store.p2pId=this.store.p2pId+1,this.establishPromise=this.establish()}async establish(){try{const e=await this.peerConnection.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0});if(!e.sdp)throw new Error(\"Cannot get initialOffer.sdp when trying to establish PeerConnection.\");const t=Tx(e.sdp),i=gx(e.sdp,{filterRTX:!this.useRTX,filterVideoFec:RC(\"FILTER_VIDEO_FEC\"),filterAudioFec:RC(\"FILTER_AUDIO_FEC\"),filterAudioCodec:[\"opus\"]});return this.localCapabilities=i,this.initialOffer=e,PV(PV({},t),{},{rtpCapabilities:{send:{audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},recv:{audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},sendrecv:i},offerSDP:e.sdp})}catch(e){throw new Kg(Hg.GET_LOCAL_CONNECTION_PARAMS_FAILED,e.toString())}}async connect(e,t,i,n,r,s){try{if(!this.initialOffer)throw new Error(\"Cannot establish P2PConnection without initial offer.\");this.remoteSDP=new class{constructor(e){sh(this,\"sessionDesc\",void 0),sh(this,\"localCapabilities\",void 0),sh(this,\"rtpCapabilities\",void 0),sh(this,\"candidates\",void 0),sh(this,\"iceParameters\",void 0),sh(this,\"dtlsParameters\",void 0),sh(this,\"setup\",void 0),sh(this,\"currentMidIndex\",void 0),sh(this,\"cname\",void 0),e=YT(e);const{remoteIceParameters:t,remoteDtlsParameters:i,candidates:n,remoteRTPCapabilities:r,remoteSetup:s,localCapabilities:o,sdkCodec:a,cname:c}=e,d=JU.parse(\"v=0\\no=- 0 0 IN IP4 127.0.0.1\\ns=AgoraGateway\\nt=0 0\\na=group:BUNDLE audio video\\na=msid-semantic: WMS\\na=ice-lite\\nm=audio 9 UDP/TLS/RTP/SAVPF 0\\nc=IN IP4 127.0.0.1\\na=rtcp:9 IN IP4 0.0.0.0\\na=sendrecv\\na=rtcp-mux\\na=rtcp-rsize\\na=mid:audio\\nm=video 9 UDP/TLS/RTP/SAVPF 0\\nc=IN IP4 127.0.0.1\\na=rtcp:9 IN IP4 0.0.0.0\\na=sendrecv\\na=rtcp-mux\\na=rtcp-rsize\\na=mid:video\\n\");this.rtpCapabilities=r,this.candidates=n,this.iceParameters=t,this.dtlsParameters=i,this.setup=s,this.localCapabilities=o,this.cname=c;for(let e=0;ee.payloadType.toString(10)));let e=r.videoCodecs.filter((e=>{var t,i;return null===(t=e.rtpMap)||void 0===t?void 0:bn(i=t.encodingName.toLowerCase()).call(i,a)}));0===e.length&&(e=r.videoCodecs),o.attributes.payloads=e,o.attributes.extmaps=r.videoExtensions}\"audio\"===o.media.mediaType&&(o.media.fmts=r.audioCodecs.map((e=>e.payloadType.toString(10))),o.attributes.payloads=r.audioCodecs,o.attributes.extmaps=r.audioExtensions),d.mediaDescriptions[e]=this.mungMediaDesc(o)}this.sessionDesc=d,this.currentMidIndex=d.mediaDescriptions.length-1}toString(){return JU.print(this.sessionDesc)}send(e,t,i){const{ssrcs:n,ssrcGroups:r}=Cx(t,this.cname),s=this.sessionDesc.mediaDescriptions.find((t=>e===av.VIDEO?\"video\"===t.media.mediaType:\"audio\"===t.media.mediaType)),o=n[0].attributes.label,a=n[0].attributes.mslabel;return s.attributes.ssrcs=s.attributes.ssrcs.concat(n),s.attributes.ssrcGroups=s.attributes.ssrcGroups.concat(r),{id:o,mslabel:a}}batchSend(e){return e.map((e=>{let{kind:t,ssrcMsg:i}=e;return this.send(t,i,void 0)}))}stopSending(e){this.sessionDesc.mediaDescriptions.forEach((t=>{const i=[],n=[],r=[];t.attributes.ssrcs.forEach((t=>{bn(e).call(e,t.attributes.label||\"\")?r.push(t):i.push(t)})),t.attributes.ssrcGroups.forEach((e=>{var t;bn(t=r.map((e=>e.ssrcId))).call(t,e.ssrcIds[0])||n.push(e)})),t.attributes.ssrcs=i,t.attributes.ssrcGroups=n}))}mute(e){const t=this.sessionDesc.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error(\"mediaDescription not found with \".concat(e,\" in remote SDP when calling RemoteSDP.mute.\"));t.attributes.direction=\"inactive\"}unmute(e){const t=this.sessionDesc.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error(\"mediaDescription not found with \".concat(e,\" in remote SDP when calling RemoteSDP.unmute.\"));t.attributes.direction=\"sendonly\"}receive(e,t,i){e.forEach(((e,t)=>{const i=e._mediaStreamTrack,n=this.sessionDesc.mediaDescriptions.findIndex((e=>e.attributes.mid===i.kind)),r=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[n],e);this.sessionDesc.mediaDescriptions[n]=r}))}stopReceiving(e){}updateCandidates(e){e===cv.TCP?this.candidates.forEach((e=>{-1===this.candidates.findIndex((t=>\"tcp\"===t.transport&&t.connectionAddress===e.connectionAddress&&t.port===e.port))&&this.candidates.push(NV(NV({},e),{},{foundation:\"tcpcandidate\",priority:Number(e.priority)-1+\"\",transport:\"tcp\",port:Number(e.port)+90+\"\"}))})):this.candidates=this.candidates.filter((e=>\"tcp\"!==e.transport));for(const e of this.sessionDesc.mediaDescriptions)e.attributes.candidates=this.candidates}restartICE(e){e=YT(e),this.iceParameters=e,this.sessionDesc.mediaDescriptions.forEach((t=>{t.attributes.iceUfrag=e.iceUfrag,t.attributes.icePwd=e.icePwd}))}predictReceivingMids(e){const t=[];for(let i=0;it.attributes.mid===e));if(-1!==i){const e=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[i],t);this.sessionDesc.mediaDescriptions[i]=e}}bumpMid(e){this.currentMidIndex+=e}updateTrackLabel(e,t,i){const n=this.sessionDesc.mediaDescriptions.find((t=>e===av.VIDEO?\"video\"===t.attributes.mid:\"audio\"===t.attributes.mid));if(n){const e=n.attributes.ssrcs.find((e=>e.attributes.label===t));var r;e&&(e.attributes.label=i,null===(r=e.attributes.msid)||void 0===r||r.replace(t,i))}}mungMediaDesc(e){const t=YT(e);return vx(t),function(e){const t=e.attributes.extmaps.find((e=>\"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01\"===e.extensionName));t&&e.attributes.extmaps.splice(e.attributes.extmaps.indexOf(t),1),e.attributes.payloads.forEach((e=>{const t=e.rtcpFeedbacks.findIndex((e=>\"transport-cc\"===e.type));-1!==t&&e.rtcpFeedbacks.splice(t,1)}))}(t),t}getSSRC(e){for(const t of this.sessionDesc.mediaDescriptions)for(const i of t.attributes.ssrcs)if(i.attributes.label===e)return[i]}}({remoteIceParameters:e,remoteDtlsParameters:t,candidates:i,remoteRTPCapabilities:n.send,remoteSetup:r,localCapabilities:this.localCapabilities,sdkCodec:this.store.codec,cname:s});const o=this.remoteSDP.toString();await this.peerConnection.setLocalDescription(this.initialOffer),await this.peerConnection.setRemoteDescription({type:\"answer\",sdp:o})}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,\"P2PConnection.connect failed; \".concat(e.toString()))}}async updateRemoteRTPCapabilities(e,t){throw new Kg(Hg.NOT_SUPPORTED,\"Planb mode does not support createDataChannels.\")}send(e,t){var i=this;return PU((function*(){const n=yield IU(i.mutex.lock());try{if(!i.remoteSDP)throw new Error(\"Cannot call P2PConnection.send before remote SDP created\");const r=e.map((e=>i.peerConnection.addTrack(e._mediaStreamTrack))),s=yield IU(i.peerConnection.createOffer()),o=JU.parse(s.sdp),a=e.map((e=>{const t=e._mediaStreamTrack,n=o.mediaDescriptions.find((e=>e.attributes.mid===t.kind));if(!n)throw new Error(\"Cannot extract ssrc from mediaDescription.\");return function(e,t,i){const n=e.attributes.ssrcs.filter((e=>e.attributes.label===t)),r=e.attributes.ssrcGroups;if(0===n.length)throw new Error(\"Cannot extract ssrc from plan-b SDP.\");if(r&&n.length>1){const e=r.find((e=>-1!==e.ssrcIds.indexOf(n[0].ssrcId)));return e?[{ssrcId:e.ssrcIds[0],rtx:i?e.ssrcIds[1]:void 0}]:[{ssrcId:n[0].ssrcId}]}return[{ssrcId:n[0].ssrcId}]}(n,t.id,i.useRTX)}));let c;try{c=yield a}catch(e){throw r.forEach((e=>{bg()&&e.replaceTrack(null),i.peerConnection.removeTrack(e)})),e}const d=i.mungSendOfferSDP(s.sdp,e);i.remoteSDP.receive(e,t,c);const l=i.remoteSDP.toString();return yield IU(i.peerConnection.setLocalDescription({type:\"offer\",sdp:d})),yield IU(i.applySendEncodings(r,e)),yield IU(i.peerConnection.setRemoteDescription({type:\"answer\",sdp:l})),e.map(((e,t)=>{const i=e._mediaStreamTrack.id;return{localSSRC:a[t],id:i}}))}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,\"P2PConnection.send failed; \".concat(e.toString()))}finally{n()}}))()}async stopSending(e){try{if(!this.remoteSDP)throw new Error(\"Cannot call P2PConnection.stopSending before remote SDP created\");const t=this.peerConnection.getSenders().filter((t=>{var i;return-1!==e.indexOf((null===(i=t.track)||void 0===i?void 0:i.id)||\"\")}));if(t.length!==e.length)throw new Error(\"Transceivers' length doesn't match mids' length when trying to call P2PConnection.stopSending.\");t.map((e=>{bg()&&e.replaceTrack(null),this.peerConnection.removeTrack(e)}));const i=await this.peerConnection.createOffer();await this.peerConnection.setLocalDescription(i),this.remoteSDP.stopReceiving(e);const n=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:\"answer\",sdp:n})}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,\"P2PConnection.stopSending failed; \".concat(e.toString()))}}async receive(e,t,i,n){try{if(!this.remoteSDP)throw new Error(\"Cannot call P2PConnection.receive \".concat(e,\" before remoteSDP created.\"));const{id:i,mslabel:r}=this.remoteSDP.send(e,t,n),s=new cg(((t,n)=>{const s=setTimeout((()=>{n(new Error(\"Cannot receive track, id: \".concat(i)))}),1e4),o=n=>{const a=Sg();if((\"Safari\"===a.name&&11===Number(a.version)||Og())&&n.track.id!==i&&n.streams[0].id===r){var c;const r=n.streams[0].getTracks()[0];return null===(c=this.remoteSDP)||void 0===c||c.updateTrackLabel(e,i,n.track.id),this.peerConnection.removeEventListener(\"track\",o),clearTimeout(s),void t(r)}if(n.track.id===i)return this.peerConnection.removeEventListener(\"track\",o),clearTimeout(s),void t(n.track)};this.peerConnection.addEventListener(\"track\",o)})),o=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:\"offer\",sdp:o});const a=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(a);return{track:await s,id:i}}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,\"P2PConnection.receive failed; \".concat(e.toString()))}}async stopReceiving(e){try{if(!this.remoteSDP)throw new Error(\"Cannot call P2PConnection.stopReceiving before remote SDP created.\");this.remoteSDP.stopSending(e);const t=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:\"offer\",sdp:t});const i=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(i)}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,\"P2PConnection stopReceiving failed; \".concat(e.toString()))}}async muteRemote(e){}async unmuteRemote(e){}async muteLocal(e){try{if(!this.remoteSDP)throw new Error(\"Cannot call P2PConnection.muteLocal before remote SDP created.\");const t=this.peerConnection.getSenders().filter((t=>{var i;return-1!==e.indexOf((null===(i=t.track)||void 0===i?void 0:i.id)||\"\")}));if(t.length!==e.length)throw new Error(\"sender' length doesn't match mids' length.\");t.map((e=>{if(bg()&&e.track)e.track.enabled=!1;else{const t=e.getParameters();t.encodings.forEach((e=>e.active=!1)),e.setParameters(t)}}))}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,\"P2PConnection.muteLocal failed; \".concat(e.toString()))}}async unmuteLocal(e){try{if(!this.remoteSDP)throw new Error(\"Cannot call P2PConnection.unmuteLocal before remote SDP created.\");const t=this.peerConnection.getSenders().filter((t=>{var i;return-1!==e.indexOf((null===(i=t.track)||void 0===i?void 0:i.id)||\"\")}));if(t.length!==e.length)throw new Error(\"Senders' length doesn't match mids' length.\");t.map((async e=>{if(bg()&&e.track)e.track.enabled=!0;else{const t=e.getParameters();t.encodings.forEach((e=>e.active=!0)),await e.setParameters(t)}}));const i=await this.peerConnection.createOffer();await this.peerConnection.setLocalDescription(i);const n=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:\"answer\",sdp:n})}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,\"P2PConnection.unmuteLocal failed; \".concat(e.toString()))}}restartICE(e){var t=this;return PU((function*(){const i=yield IU(t.mutex.lock(\"From P2PConnection.restartICE\"));try{if(!t.remoteSDP)throw new Error(\"Cannot restartICE before remoteSDP created.\");if(IA().supportPCSetConfiguration){const i=t.peerConnection.getConfiguration(),n=e===cv.RELAY?\"relay\":\"all\";i.iceTransportPolicy!==n&&(jC.debug(\"[\".concat(t.store.clientId,\"] restartICE change iceTransportPolicy from [\").concat(i.iceTransportPolicy,\"] to [\").concat(n,\"]\")),i.iceTransportPolicy=n,t.peerConnection.setConfiguration(i))}else if(e===cv.RELAY)return;e!==cv.RELAY&&t.remoteSDP.updateCandidates(e);const n=yield IU(t.peerConnection.createOffer({iceRestart:!0}));if(!n.sdp)throw new Error(\"Cannot restartICE because restart offer SDP does not exist.\");const r=Tx(n.sdp),{remoteIceParameters:s}=yield r.iceParameters;t.remoteSDP.restartICE(s);const o=t.remoteSDP.toString();yield IU(t.peerConnection.setLocalDescription(n)),yield IU(t.peerConnection.setRemoteDescription({type:\"answer\",sdp:o}))}catch(e){jC.warning(\"[\".concat(t.store.clientId,\"] restart ICE failed, abort operation\"),e)}finally{i()}}))()}close(){var e;this.peerConnection.close(),null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,\"closed\"),this.unbindPCEvents(),this.unbindStatsEvents(),this.removeAllListeners(),this.statsFilter.destroy()}getStats(){return this.statsFilter.getStats()}getRemoteVideoIsReady(e){return this.statsFilter.getVideoIsReady(e)}async updateEncoderConfig(e,t){try{if(!this.remoteSDP)throw new Error(\"Cannot call P2PConnection.updateEncoderConfig before remote SDP created.\");const e=await this.peerConnection.createOffer(),i=this.mungSendOfferSDP(e.sdp,[t]);this.remoteSDP.updateRecvMedia(t._mediaStreamTrack.kind,t);const n=this.remoteSDP.toString();await this.peerConnection.setLocalDescription({type:\"offer\",sdp:i}),await this.peerConnection.setRemoteDescription({type:\"answer\",sdp:n})}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,e.toString())}}async updateSendParameters(e,t){const i=this.peerConnection.getSenders().filter((t=>{var i;return(null===(i=t.track)||void 0===i?void 0:i.id)===e}));1===i.length&&await this.applySendEncodings(i,[t])}setStatsRemoteVideoIsReady(e,t){this.statsFilter.setVideoIsReady2(e,t)}async replaceTrack(e,t){const i=this.peerConnection.getSenders().find((e=>{var i;return(null===(i=e.track)||void 0===i?void 0:i.id)===t}));i&&await i.replaceTrack(e._mediaStreamTrack)}createDataChannels(e,t){throw new Kg(Hg.NOT_SUPPORTED,\"Planb mode does not support createDataChannels.\")}stopDataChannels(e){throw new Kg(Hg.NOT_SUPPORTED,\"Planb mode does not support stopDataChannels.\")}bindPCEvents(){this.peerConnection.oniceconnectionstatechange=()=>{var e;null===(e=this.onICEConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.iceConnectionState)},this.peerConnection.onconnectionstatechange=()=>{var e;null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.connectionState)},this.peerConnection.onicecandidate=e=>{e.candidate?this.localCandidateCount+=1:(this.peerConnection.onicecandidate=null,this.allCandidatesReceived=!0,jC.debug(\"[\".concat(this.store.clientId,\"] [pc-\").concat(this.store.p2pId,\"] local candidate count\"),this.localCandidateCount))},setTimeout((()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,jC.debug(\"[\".concat(this.store.clientId,\"] [pc-\").concat(this.store.p2pId,\"] onicecandidate timeout, local candidate count\"),this.localCandidateCount))}),RC(\"CANDIDATE_TIMEOUT\"))}unbindPCEvents(){this.peerConnection.oniceconnectionstatechange=null,this.peerConnection.onconnectionstatechange=null,this.peerConnection.onsignalingstatechange=null,this.peerConnection.onicecandidateerror=null,this.peerConnection.onicecandidate=null,this.peerConnection.ontrack=null}static resolvePCConfiguration(e){const t={iceServers:[],sdpSemantics:\"plan-b\"};return e.iceServers?t.iceServers=e.iceServers:e.turnServer&&\"off\"!==e.turnServer.mode&&(RT(e.turnServer.servers)?t.iceServers=e.turnServer.servers:(t.iceServers&&t.iceServers.push(...LV.turnServerConfigToIceServers(e.turnServer.servers)),RC(\"USE_TURN_SERVER_OF_GATEWAY\")&&t.iceServers&&e.turnServer.serversFromGateway&&t.iceServers.push(...LV.turnServerConfigToIceServers(e.turnServer.serversFromGateway)),e.turnServer.servers.concat(e.turnServer.serversFromGateway||[]).forEach((e=>{e.forceturn&&(t.iceTransportPolicy=\"relay\")})))),t}static turnServerConfigToIceServers(e){const t=[];return e.forEach((e=>{e.security?e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:\"password\",urls:\"turns:\".concat(e.turnServerURL,\":\").concat(e.tcpport,\"?transport=tcp\")}):(e.udpport&&t.push({username:e.username,credential:e.password,credentialType:\"password\",urls:\"turn:\".concat(e.turnServerURL,\":\").concat(e.udpport,\"?transport=udp\")}),e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:\"password\",urls:\"turn:\".concat(e.turnServerURL,\":\").concat(e.tcpport,\"?transport=tcp\")}))})),t}async updateRtpSenderEncodings(e,t){var i;if(!t){t=this.peerConnection.getSenders().find((t=>{var i;return(null===(i=t.track)||void 0===i?void 0:i.id)===e._mediaStreamTrack.id}))}if(!t)return jC.warn(\"[\".concat(e.getTrackId(),\"] no rtpSender found}\"));if(!IA().supportSetRtpSenderParameters)return jC.warn(\"Browser not support set rtp-sender parameters\");const n={},r={};if(e instanceof Rw)switch(e._optimizationMode){case\"motion\":n.degradationPreference=\"maintain-framerate\";break;case\"detail\":n.degradationPreference=\"maintain-resolution\";break;default:n.degradationPreference=\"balanced\"}if(RC(\"DSCP_TYPE\")&&jg()){var s;const e=RC(\"DSCP_TYPE\");bn(s=[\"very-low\",\"low\",\"medium\",\"high\"]).call(s,e)&&(r.networkPriority=e)}const o=t.getParameters(),a=null===(i=o.encodings)||void 0===i?void 0:i[0];a&&Object.assign(a,r),Object.assign(o,n),jC.debug(\"[\".concat(e.getTrackId(),\"] updateRtpSenderEncodings: \").concat(JSON.stringify(o.encodings))),await t.setParameters(o)}async applySendEncodings(e,t){try{if(!IA().supportSetRtpSenderParameters)return;if(e.length!==t.length)return;for(let i=0;i{const n=e._mediaStreamTrack,r=i.mediaDescriptions.find((e=>e.attributes.mid===n.kind));r&&Ix(r,e)})),JU.print(i)}bindStatsEvents(){this.statsFilter.onFirstAudioReceived=e=>{var t;null===(t=this.onFirstAudioReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoReceived=e=>{var t;null===(t=this.onFirstVideoReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstAudioDecoded=e=>{var t;null===(t=this.onFirstAudioDecoded)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoDecoded=(e,t,i)=>{var n;null===(n=this.onFirstVideoDecoded)||void 0===n||n.call(this,e,t,i)},this.statsFilter.onSelectedLocalCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedLocalCandidateChanged)||void 0===i||i.call(this,e,t)},this.statsFilter.onSelectedRemoteCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedRemoteCandidateChanged)||void 0===i||i.call(this,e,t)}}unbindStatsEvents(){this.statsFilter.onFirstAudioReceived=void 0,this.statsFilter.onFirstVideoReceived=void 0,this.statsFilter.onFirstAudioDecoded=void 0,this.statsFilter.onFirstVideoDecoded=void 0,this.statsFilter.onSelectedLocalCandidateChanged=void 0,this.statsFilter.onSelectedRemoteCandidateChanged=void 0}async batchReceive(e){try{if(!this.remoteSDP)throw new Error(\"Cannot call P2PConnection.batchReceive before remoteSDP created.\");const t=this.remoteSDP.batchSend(e).map(((t,i)=>{let{id:n,mslabel:r}=t;const{kind:s}=e[i];return new cg(((e,t)=>{const i=setTimeout((()=>{t(new Error(\"Cannot receive track, id: \".concat(n)))}),1e4),o=t=>{const a=Sg();if(\"Safari\"===a.name&&11===Number(a.version)&&t.track.id!==n&&t.streams[0].id===r){var c;const r=t.streams[0].getTracks()[0];return null===(c=this.remoteSDP)||void 0===c||c.updateTrackLabel(s,n,t.track.id),this.peerConnection.removeEventListener(\"track\",o),clearTimeout(i),void e({track:r,id:n})}if(t.track.id===n)return this.peerConnection.removeEventListener(\"track\",o),clearTimeout(i),void e({track:t.track,id:n})};this.peerConnection.addEventListener(\"track\",o)}))})),i=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:\"offer\",sdp:i});const n=await this.peerConnection.createAnswer();return await this.peerConnection.setLocalDescription(n),await cg.all(t)}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,\"P2PConnection.receive failed; \".concat(e.toString()))}}async getRemoteSSRC(e){if(!this.remoteSDP)return;const t=this.remoteSDP.getSSRC(e);return null==t?void 0:t[0].ssrcId}setConfiguration(e){if(IA().supportPCSetConfiguration){const t=LV.resolvePCConfiguration(e);this.peerConnection.setConfiguration(t)}}}function kV(e,t,i){const n=e[t];if(\"function\"!=typeof n)throw new Error(\"Cannot use mutex on object property.\");return i.value=async function(){const e=this.mutex,i=await e.lock(\"Locking from P2PConnection.\".concat(t));try{for(var r=arguments.length,s=new Array(r),o=0;oe.rtpMap&&e.rtpMap.encodingName.toLowerCase()||\"\")).filter((e=>{var t;return bn(t=Object.keys(bC)).call(t,e)})))]}constructor(e,t){super(e,t),sh(this,\"store\",void 0),sh(this,\"peerConnection\",void 0),sh(this,\"remoteSDP\",void 0),sh(this,\"initialOffer\",void 0),sh(this,\"transportEventReceiver\",void 0),sh(this,\"statsFilter\",void 0),sh(this,\"useXR\",RC(\"USE_XR\")),sh(this,\"localCapabilities\",void 0),sh(this,\"remoteCodecs\",void 0),sh(this,\"localCandidateCount\",0),sh(this,\"allCandidatesReceived\",!1),sh(this,\"dataStreamChannelMap\",new Map),sh(this,\"establishPromise\",void 0),sh(this,\"recoveredDataChannelIds\",[]),sh(this,\"currentDataChannelId\",1),sh(this,\"mutex\",new pS(\"P2PConnection-mutex\")),this.store=t,this.peerConnection=new RTCPeerConnection(jV.resolvePCConfiguration(e),{optional:[{googDscp:!0}]}),this.statsFilter=Ex(this.peerConnection,RC(\"STATS_UPDATE_INTERVAL\"),void 0,wg()?1200:void 0),this.bindPCEvents(),this.bindStatsEvents(),this.store.p2pId=this.store.p2pId+1,this.establishPromise=this.establish()}async updateRemoteRTPCapabilities(e,t){if(this.remoteCodecs=t,!this.remoteSDP)return void jC.debug(\"[P2PConnection] cannot updateRemoteRTPCapabilities before remote SDP created, local codecs: \".concat(this.localCodecs,\", codecs: \").concat(t));if(this.remoteSDP.updateRemoteCodec(e,t,this.store.codec)){const e=await this.peerConnection.createOffer(),t=this.logSDPExchange(e.sdp||\"\",\"offer\",\"local\",\"muteLocal\");await this.peerConnection.setLocalDescription(e);const i=this.remoteSDP.toString();null==t||t(i),await this.peerConnection.setRemoteDescription({type:\"answer\",sdp:i})}else jC.debug(\"[P2PConnection] updateRemoteRTPCapabilities no need to exchange SDP.\")}async establish(){try{this.peerConnection.addTransceiver(\"video\",{direction:\"recvonly\"}),this.peerConnection.addTransceiver(\"audio\",{direction:\"recvonly\"});const e=await this.peerConnection.createOffer();if(!e.sdp)throw new Error(\"Cannot get initialOffer.sdp when trying to establish PeerConnection.\");const t=Tx(e.sdp),i=await Ox({filterRTX:!RC(\"USE_PUB_RTX\")&&!RC(\"USE_SUB_RTX\"),filterVideoFec:RC(\"FILTER_VIDEO_FEC\"),filterAudioFec:RC(\"FILTER_AUDIO_FEC\"),filterVideoCodec:RC(\"FILTER_VIDEO_CODEC\")},{useXR:this.useXR});return this.localCapabilities=Px(i),this.initialOffer=e,BV(BV({},t),{},{rtpCapabilities:i,offerSDP:e.sdp})}catch(e){throw new Kg(Hg.GET_LOCAL_CONNECTION_PARAMS_FAILED,e.toString())}}async connect(e,t,i,n,r,s){try{if(!this.initialOffer)throw new Error(\"Cannot establish P2PConnection without initial offer.\");this.remoteSDP=new class{get localCapabilities(){return YT(this._localCapabilities)}get rtpCapabilities(){return YT(this._rtpCapabilities)}get candidates(){return YT(this._candidates)}get iceParameters(){return YT(this._iceParameters)}get dtlsParameters(){return YT(this._dtlsParameters)}constructor(e){sh(this,\"sessionDesc\",void 0),sh(this,\"_localCapabilities\",void 0),sh(this,\"_rtpCapabilities\",void 0),sh(this,\"_candidates\",void 0),sh(this,\"_iceParameters\",void 0),sh(this,\"_dtlsParameters\",void 0),sh(this,\"setup\",void 0),sh(this,\"currentMidIndex\",void 0),sh(this,\"cname\",void 0),sh(this,\"firefoxSsrcMidMap\",new Map),e=YT(e);const{remoteIceParameters:t,remoteDtlsParameters:i,candidates:n,remoteRTPCapabilities:r,remoteSetup:s,localCapabilities:o,cname:a}=e,c=JU.parse(\"v=0\\no=- 0 0 IN IP4 127.0.0.1\\ns=AgoraGateway\\nt=0 0\\na=group:BUNDLE 0 1\\na=msid-semantic: WMS\\na=ice-lite\\nm=video 9 UDP/TLS/RTP/SAVPF 0\\nc=IN IP4 127.0.0.1\\na=rtcp:9 IN IP4 0.0.0.0\\na=sendonly\\na=rtcp-mux\\na=rtcp-rsize\\na=mid:0\\nm=audio 9 UDP/TLS/RTP/SAVPF 0\\nc=IN IP4 127.0.0.1\\na=rtcp:9 IN IP4 0.0.0.0\\na=sendonly\\na=rtcp-mux\\na=rtcp-rsize\\na=mid:1\\n\");this._rtpCapabilities=r,this._candidates=n,this._iceParameters=t,this._dtlsParameters=i,this._localCapabilities=o,this.setup=s,this.cname=a;const d=this.rtpCapabilities.send;for(const e of c.mediaDescriptions){if(e.attributes.iceUfrag=t.iceUfrag,e.attributes.icePwd=t.icePwd,e.attributes.fingerprints=i.fingerprints,e.attributes.candidates=n,e.attributes.setup=s,\"video\"===e.media.mediaType&&(e.media.fmts=d.videoCodecs.map((e=>e.payloadType.toString(10))),e.attributes.payloads=d.videoCodecs,e.attributes.extmaps=d.videoExtensions,RC(\"PRELOAD_MEDIA_COUNT\")>0)){const{ssrcs:t,ssrcGroups:i}=Cx([{ssrcId:VV,rtx:RC(\"USE_SUB_RTX\")?40001:void 0}],this.cname);e.attributes.ssrcs=t,e.attributes.ssrcGroups=i}if(\"audio\"===e.media.mediaType&&(e.media.fmts=d.audioCodecs.map((e=>e.payloadType.toString(10))),e.attributes.payloads=d.audioCodecs,e.attributes.extmaps=d.audioExtensions,Lx(e),RC(\"PRELOAD_MEDIA_COUNT\")>0)){const{ssrcs:t,ssrcGroups:i}=Cx([{ssrcId:2e4}],this.cname);e.attributes.ssrcs=t,e.attributes.ssrcGroups=i}}this.sessionDesc=c,this.currentMidIndex=c.mediaDescriptions.length-1}preloadRemoteMedia(){const e=RC(\"PRELOAD_MEDIA_COUNT\");this.rtpCapabilities;const t=this.candidates,i=this.dtlsParameters,n=this.iceParameters,r=this.rtpCapabilities.send;for(let s=1;se.payloadType.toString(10)))},connections:[{nettype:\"IN\",addrtype:\"IP4\",address:\"127.0.0.1\"}],bandwidths:[],attributes:{iceUfrag:n.iceUfrag,icePwd:n.icePwd,unrecognized:[],candidates:t,extmaps:r.videoExtensions,fingerprints:i.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:d,ssrcGroups:l,rtcpFeedbackWildcards:[],payloads:r.videoCodecs,rtcp:{port:\"9\",netType:\"IN\",addressType:\"IP4\",address:\"0.0.0.0\"},setup:this.setup,direction:\"sendonly\",rtcpMux:!0,rtcpRsize:!0,mid:\"\".concat(2*s)}}),this.sessionDesc.mediaDescriptions.push({media:{mediaType:\"audio\",port:xV,protos:[\"UDP\",\"TLS\",\"RTP\",\"SAVPF\"],fmts:r.audioCodecs.map((e=>e.payloadType.toString(10)))},connections:[{nettype:\"IN\",addrtype:\"IP4\",address:\"127.0.0.1\"}],bandwidths:[],attributes:{iceUfrag:n.iceUfrag,icePwd:n.icePwd,unrecognized:[],candidates:t,extmaps:r.audioExtensions,fingerprints:i.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:a,ssrcGroups:c,rtcpFeedbackWildcards:[],payloads:r.audioCodecs,rtcp:{port:\"9\",netType:\"IN\",addressType:\"IP4\",address:\"0.0.0.0\"},setup:this.setup,direction:\"sendonly\",rtcpMux:!0,rtcpRsize:!0,mid:\"\".concat(2*s+1)}}),this.currentMidIndex+=2}this.updateBundleMids()}toString(){return JU.print(this.sessionDesc)}send(e,t,i,n){const{ssrcs:r,ssrcGroups:s}=Cx(t,this.cname,RC(\"SYNC_GROUP\")?i:void 0),o=this.findPreloadMediaDesc(r);if(o){if(wg()&&this.firefoxSsrcMidMap.set(r[0].ssrcId,o.attributes.mid),n&&(n.twcc||n.remb)){const e=this.sessionDesc.mediaDescriptions.indexOf(o);return this.sessionDesc.mediaDescriptions[e]=this.mungSendMediaDesc(o,n),{mid:o.attributes.mid,needExchangeSDP:!0}}return{mid:o.attributes.mid,needExchangeSDP:!1}}{const t=this.findAvailableMediaIndex(e,r);let i;return-1===t||1===t&&(bg()||Lg())||0===t&&RC(\"USE_SUB_RTX\")||kg()?(i=this.createOrRecycleSendMedia(e,r,s,\"sendonly\",n),this.updateBundleMids()):(i=YT(this.sessionDesc.mediaDescriptions[t]),i.attributes.direction=\"sendonly\",i.attributes.ssrcs=r,i.attributes.ssrcGroups=s,this.sessionDesc.mediaDescriptions[t]=this.mungSendMediaDesc(i,n)),wg()&&this.firefoxSsrcMidMap.set(r[0].ssrcId,i.attributes.mid),{mid:i.attributes.mid,needExchangeSDP:!0}}}sendDataChannel(){const{mediaDesc:e,needExchangeSDP:t}=this.createOrRecycleDataChannel();return this.updateBundleMids(),{mid:e.attributes.mid,needExchangeSDP:t}}batchSend(e){const t=e.map((e=>{let{kind:t,ssrcMsg:i,mslabel:n}=e;return this.send(t,i,n)})),i=[];let n=!1;return t.forEach((e=>{let{mid:t,needExchangeSDP:r}=e;r&&(n=!0),i.push(t)})),{mids:i,needExchangeSDP:n}}stopSending(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>t.attributes.mid&&-1!==e.indexOf(t.attributes.mid)));if(t.length!==e.length)throw new Error(\"mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.stopSending.\");t.forEach((e=>{\"0\"===e.attributes.mid||wg()||kg()?e.attributes.ssrcs=[]:(e.attributes.ssrcs=[],e.attributes.direction=\"inactive\",e.media.port=\"0\")})),this.updateBundleMids()}mute(e){const t=this.sessionDesc.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error(\"mediaDescription not found with \".concat(e,\" in remote SDP when calling RemoteSDP.mute.\"));t.attributes.direction=\"inactive\"}unmute(e){const t=this.sessionDesc.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error(\"mediaDescription not found with \".concat(e,\" in remote SDP when calling RemoteSDP.unmute.\"));t.attributes.direction=\"sendonly\"}muteRemote(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>bn(e).call(e,t.attributes.mid||\"\")));if(t.length!==e.length)throw new Error(\"mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.\");t.forEach((e=>{e.attributes.direction=\"inactive\"}))}unmuteRemote(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>bn(e).call(e,t.attributes.mid||\"\")));if(t.length!==e.length)throw new Error(\"mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.\");t.forEach((e=>{e.attributes.direction=\"recvonly\"}))}receive(e,t,i,n){e.forEach(((e,r)=>{this.createOrRecycleRecvMedia(e,[],\"recvonly\",t,i,n[r])})),this.updateBundleMids()}stopReceiving(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>-1!==e.indexOf(t.attributes.mid)));if(t.length!==e.length)throw new Error(\"MediaDescriptions' length doesn't match mids's length when calling RemoteSDP.receive.\");t.forEach((e=>{e.media.port=\"0\",e.attributes.direction=\"inactive\"})),this.updateBundleMids()}updateCandidates(e){const t=this._candidates.filter((e=>\"udp\"===e.transport));if(e===cv.TCP){if(0===t.length)return;if(RC(\"TCP_CANDIDATE_ONLY\")){const e=this._candidates.filter((e=>\"tcp\"===e.transport));t.forEach((t=>{-1===e.findIndex((e=>e.connectionAddress===t.connectionAddress))&&e.push(UV(UV({},t),{},{foundation:\"tcpcandidate\",priority:Number(t.priority)-1+\"\",transport:\"tcp\",port:Number(t.port)+90+\"\"}))})),this._candidates=e}else{const e=[];t.forEach((t=>{e.push(UV(UV({},t),{},{foundation:\"tcpcandidate\",priority:Number(t.priority)-1+\"\",transport:\"tcp\",port:Number(t.port)+90+\"\"}))})),this._candidates=[...t,...e]}}else if(e===cv.RELAY){if(0!==t.length)return;{const e=this._candidates.filter((e=>\"tcp\"===e.transport));e.forEach((e=>{t.push(UV(UV({},e),{},{foundation:\"udpcandidate\",priority:Number(e.priority)+1+\"\",transport:\"udp\",port:Number(e.port)-90+\"\"}))})),this._candidates=[...t,...e]}}else 0===t.length?(this._candidates.filter((e=>\"tcp\"===e.transport)).forEach((e=>{t.push(UV(UV({},e),{},{foundation:\"udpcandidate\",priority:Number(e.priority)+1+\"\",transport:\"udp\",port:Number(e.port)-90+\"\"}))})),this._candidates=t):this._candidates=this._candidates.filter((e=>\"tcp\"!==e.transport));for(const e of this.sessionDesc.mediaDescriptions)e.attributes.candidates=this.candidates}restartICE(e){e=YT(e),this._iceParameters=e,this.sessionDesc.mediaDescriptions.forEach((t=>{t.attributes.iceUfrag=e.iceUfrag,t.attributes.icePwd=e.icePwd}))}predictReceivingMids(e){const t=[];for(let i=0;i{const n=i.media.mediaType===e&&\"0\"!==i.media.port&&(\"sendonly\"===i.attributes.direction||\"sendrecv\"===i.attributes.direction)&&0===i.attributes.ssrcs.length;if(wg()){if(n){const e=this.firefoxSsrcMidMap.get(t[0].ssrcId);return!(e||\"0\"!==i.attributes.mid&&\"1\"!==i.attributes.mid)||!(!e||e!==i.attributes.mid)}return!1}return n}))}createOrRecycleDataChannel(){for(const e of this.sessionDesc.mediaDescriptions)if(\"application\"===e.media.mediaType)return{mediaDesc:e,needExchangeSDP:!1};this.currentMidIndex+=1;const e=\"\".concat(this.currentMidIndex),t={media:{mediaType:\"application\",port:xV,protos:[\"UDP\",\"DTLS\",\"SCTP\"],fmts:[\"webrtc-datachannel\"]},connections:[{nettype:\"IN\",addrtype:\"IP4\",address:\"127.0.0.1\"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:this.candidates,extmaps:[],fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:[],ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:[],rtcp:{port:\"9\",netType:\"IN\",addressType:\"IP4\",address:\"0.0.0.0\"},setup:this.setup,mid:\"\".concat(e),sctpPort:\"5000\"}};return this.sessionDesc.mediaDescriptions.push(t),{mediaDesc:t,needExchangeSDP:!0}}createOrRecycleRecvMedia(e,t,i,n,r,s){const o=e._mediaStreamTrack.kind,a=this.rtpCapabilities.recv,c=Mx(o,a,this.localCapabilities.send,o===av.VIDEO?n:r),d=o===av.VIDEO?a.videoExtensions:a.audioExtensions;this.currentMidIndex+=1;const l=\"\".concat(this.currentMidIndex);let u={media:{mediaType:o,port:xV,protos:[\"UDP\",\"TLS\",\"RTP\",\"SAVPF\"],fmts:c.map((e=>e.payloadType.toString(10)))},connections:[{nettype:\"IN\",addrtype:\"IP4\",address:\"127.0.0.1\"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:this.candidates,extmaps:d,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:c,rtcp:{port:\"9\",netType:\"IN\",addressType:\"IP4\",address:\"0.0.0.0\"},setup:this.setup,direction:i,rtcpMux:!0,rtcpRsize:!0,mid:\"\".concat(l)}};u=this.mungRecvMediaDsec(u,e,s);const h=this.findFirstClosedMedia(o);if(h){const e=this.sessionDesc.mediaDescriptions.indexOf(h);this.sessionDesc.mediaDescriptions[e]=u}else this.sessionDesc.mediaDescriptions.push(u);return u}updateRemoteCodec(e,t,i){const n=[...new Set(this._rtpCapabilities.recv.videoCodecs.map((e=>e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||\"\")).filter((e=>{var t;return bn(t=Object.keys(bC)).call(t,e)})))],r=new Set(t);if(n.every((e=>r.has(e))))return jC.debug(\"codecs has not changed, no need to updateRemoteCodec, codecs: \".concat(t)),!1;const s=this._rtpCapabilities.recv.videoCodecs.filter((e=>t.some((t=>{var i;return bn(i=e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||\"\").call(i,t)}))));if(0===s.length)return jC.debug(\"updateRemoteCodec failed, because cannot find matched codec, remoteCapabilities codecs: \".concat(n,\" codecs: \").concat(t)),!1;const o=[...new Set(s.map((e=>e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||\"\")))];let a;if(jC.debug(\"updateRemoteCodec, from \".concat(n,\" to \").concat(o)),0===e.length)a=this.sessionDesc.mediaDescriptions.filter((e=>\"video\"===e.media.mediaType&&\"recvonly\"===e.attributes.direction));else if(a=this.sessionDesc.mediaDescriptions.filter((t=>t.attributes.mid&&bn(e).call(e,t.attributes.mid)&&\"recvonly\"===t.attributes.direction)),a.length!==e.length)return jC.debug(\"updateRemoteCodec failed, because cannot find mids, mids: \".concat(e,\", codecs: \").concat(t)),!1;this._rtpCapabilities.recv.videoCodecs=s;const c=this.localCapabilities.send,d=this.rtpCapabilities.recv,l=Mx(av.VIDEO,d,c,i);return a.forEach((e=>{const t=l.map((e=>e.payloadType.toString(10)));jC.debug(\"updateRemoteCodec mid: \".concat(e.attributes.mid,\", from \").concat(e.attributes.payloads,\" to \").concat(l)),e.attributes.payloads=l,e.media.fmts=t})),!0}createOrRecycleSendMedia(e,t,i,n,r){const s=this.rtpCapabilities.send,o=e===av.VIDEO?s.videoCodecs:s.audioCodecs,a=e===av.VIDEO?s.videoExtensions:s.audioExtensions;this.currentMidIndex+=1;const c=\"\".concat(this.currentMidIndex);let d={media:{mediaType:e,port:xV,protos:[\"UDP\",\"TLS\",\"RTP\",\"SAVPF\"],fmts:o.map((e=>e.payloadType.toString(10)))},connections:[{nettype:\"IN\",addrtype:\"IP4\",address:\"127.0.0.1\"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:this.candidates,extmaps:a,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:i,rtcpFeedbackWildcards:[],payloads:o,rtcp:{port:\"9\",netType:\"IN\",addressType:\"IP4\",address:\"0.0.0.0\"},setup:this.setup,direction:n,rtcpMux:!0,rtcpRsize:!0,mid:\"\".concat(c)}};d=this.mungSendMediaDesc(d,r);const l=this.findFirstClosedMedia(e);if(l){const e=this.sessionDesc.mediaDescriptions.indexOf(l);this.sessionDesc.mediaDescriptions[e]=d}else this.sessionDesc.mediaDescriptions.push(d);return d}updateBundleMids(){this.sessionDesc.attributes.groups[0].identificationTag=this.sessionDesc.mediaDescriptions.filter((e=>\"0\"!==e.media.port)).map((e=>e.attributes.mid))}mungRecvMediaDsec(e,t,i){const n=YT(e);return vx(n),Ix(n,t),yx(n,t),Ax(n),bx(n,i,this.localCapabilities.send),n}mungSendMediaDesc(e,t){const i=YT(e);return bx(i,t,this.localCapabilities.recv),Lx(i),i}updateRecvMedia(e,t){const i=this.sessionDesc.mediaDescriptions.findIndex((t=>t.attributes.mid===e));if(-1!==i){const e=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[i],t);this.sessionDesc.mediaDescriptions[i]=e}}bumpMid(e){this.currentMidIndex+=e}findFirstClosedMedia(e){return this.sessionDesc.mediaDescriptions.find((t=>wg()?\"0\"===t.media.port&&t.media.mediaType===e:\"0\"===t.media.port))}findPreloadMediaDesc(e){return this.sessionDesc.mediaDescriptions.find((t=>{var i;return(null===(i=t.attributes)||void 0===i||null===(i=i.ssrcs[0])||void 0===i?void 0:i.ssrcId)===e[0].ssrcId}))}getSSRC(e){var t;return null===(t=this.sessionDesc.mediaDescriptions.find((t=>t.attributes.mid===e)))||void 0===t?void 0:t.attributes.ssrcs}}({remoteIceParameters:e,remoteDtlsParameters:t,candidates:i,remoteRTPCapabilities:n,remoteSetup:r,localCapabilities:this.localCapabilities,cname:s}),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0&&this.remoteSDP.updateRemoteCodec([],this.remoteCodecs,this.store.codec);const o=this.remoteSDP.toString(),a=JU.parse(this.initialOffer.sdp),c=a.mediaDescriptions.find((e=>\"audio\"===e.media.mediaType));c&&Lx(c),this.useXR&&kx(a);const d=JU.print(a),l=this.logSDPExchange(d||\"\",\"offer\",\"local\",\"connect\");this.store.descriptionStart(),await this.peerConnection.setLocalDescription({type:\"offer\",sdp:d}),null==l||l(o),await this.peerConnection.setRemoteDescription({type:\"answer\",sdp:o});const u=this.peerConnection.getTransceivers()[0];if(null!=u&&u.receiver&&this.tryBindTransportEvents(u.receiver),RC(\"PRELOAD_MEDIA_COUNT\")>0){this.remoteSDP.preloadRemoteMedia();const e=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:\"offer\",sdp:e});const t=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(t)}}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,\"P2PConnection.connect failed; \".concat(e.toString()))}}send(e,t,i){var n=this;return PU((function*(){const r=yield IU(n.mutex.lock(\"From P2PConnection.send\"));try{if(!n.remoteSDP)throw new Error(\"Cannot call P2PConnection.send before remote SDP created\");const s=[];e.forEach((e=>{const t=n.peerConnection.addTransceiver(e._mediaStreamTrack,{direction:\"sendonly\"});s.push(t),e._updateRtpTransceiver(t)})),wg()&&!0===RC(\"SIMULCAST\")&&(yield IU(n.applySimulcastForFirefox(s,e)));const o=yield IU(n.peerConnection.createOffer()),a=n.remoteSDP.predictReceivingMids(e.length),c=n.mungSendOfferSDP(o.sdp,e,a),d=JU.parse(c),l=a.map((e=>{const t=d.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error(\"Cannot extract ssrc from mediaDescription.\");return Sx(t,RC(\"USE_PUB_RTX\"))}));let u;try{u=yield l}catch(r){u=[],n.remoteSDP.receive(e,t,i,u);const s=n.remoteSDP.toString();throw yield IU(n.peerConnection.setLocalDescription({type:\"offer\",sdp:c})),yield IU(n.peerConnection.setRemoteDescription({type:\"answer\",sdp:s})),yield IU(n.stopSending(a,!0)),r}n.remoteSDP.receive(e,t,i,u);const h=n.remoteSDP.toString(),p=n.logSDPExchange(c,\"offer\",\"local\",\"send\");return yield IU(n.peerConnection.setLocalDescription({type:\"offer\",sdp:c})),yield IU(n.applySimulcastEncodings(s,e)),yield IU(n.applySendEncodings(s,e)),null==p||p(h),yield IU(n.peerConnection.setRemoteDescription({type:\"answer\",sdp:h})),s.map(((e,t)=>{const i=a[t];return{localSSRC:l[t],id:i,transceiver:e}}))}catch(e){throw e instanceof Kg?e:new Kg(Hg.EXCHANGE_SDP_FAILED,\"P2PConnection.send failed; \".concat(e.toString()))}finally{r()}}))()}async createDataChannels(e,t){try{if(!this.remoteSDP)throw new Error(\"Cannot call P2PConnection.createDataChannels before remote SDP created\");let i=this.dataStreamChannelMap.get(e);if(i&&\"open\"===i.readyState)jC.debug(\"[P2PConnection] Channels are already available and can be reused directly.\");else{const t=this.currentDataChannelId<1023?this.currentDataChannelId++:this.recoveredDataChannelIds.shift();if(\"number\"!=typeof t)throw new Error(\"create DataChannel error, because cannot get dc id\");i=this.peerConnection.createDataChannel(\"datastream-channel\",{id:t,negotiated:!0,ordered:!1,maxRetransmits:RC(\"DATASTREAM_MAX_RETRANSMITS\")}),i.binaryType=\"arraybuffer\",this.dataStreamChannelMap.set(e,i)}t.forEach((e=>{e._updateOriginDataChannel(i)}));const{needExchangeSDP:n}=this.remoteSDP.sendDataChannel();if(n){const e=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:\"offer\",sdp:e});const t=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(t),jC.debug(\"[P2PConnection] createDataChannels by exchanging SDP.\")}else jC.debug(\"[P2PConnection] createDataChannels no need to exchange SDP.\");return}catch(e){throw e instanceof Kg?e:new Kg(Hg.EXCHANGE_SDP_FAILED,\"P2PConnection.createDataChannels failed; \".concat(e.toString()))}}async stopDataChannels(e){try{const t=this.dataStreamChannelMap.get(e);return t&&(t.id&&this.recoveredDataChannelIds.push(t.id),t.close()),void this.dataStreamChannelMap.delete(e)}catch(e){throw e instanceof Kg?e:new Kg(Hg.DATACHANNEL_FAILED,\"P2PConnection.stopDataChannels failed; \".concat(e.toString()))}}async stopSending(e,t){const i=t?void 0:await this.mutex.lock(\"From P2PConnection.stopSending\");try{if(!this.remoteSDP)throw new Error(\"Cannot call P2PConnection.stopSending before remote SDP created\");const t=this.peerConnection.getTransceivers().filter((t=>-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error(\"Transceivers' length doesn't match mids' length when trying to call P2PConnection.stopSending.\");t.map((e=>{var t;e.direction=\"inactive\",null===(t=e.stop)||void 0===t||t.call(e)}));const n=await this.peerConnection.createOffer(),r=this.logSDPExchange(n.sdp||\"\",\"offer\",\"local\",\"stopSending\");await this.peerConnection.setLocalDescription(n),this.remoteSDP.stopReceiving(e);const s=this.remoteSDP.toString();null==r||r(s),await this.peerConnection.setRemoteDescription({type:\"answer\",sdp:s})}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,\"P2PConnection.stopSending failed; \".concat(e.toString()))}finally{i&&i()}}async receive(e,t,i,n){try{if(!this.remoteSDP)throw new Error(\"Cannot call P2PConnection.receive \".concat(e,\" before remoteSDP created.\"));const{mid:r,needExchangeSDP:s}=this.remoteSDP.send(e,t,i,n);if(s){const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,\"offer\",\"remote\",\"receive\");await this.peerConnection.setRemoteDescription({type:\"offer\",sdp:t});const n=await this.peerConnection.createAnswer(),s=this.mungReceiveAnswerSDP(n.sdp,r,e);null==i||i(s||\"\"),await this.peerConnection.setLocalDescription({type:\"answer\",sdp:s}),jC.debug(\"[\".concat(this.store.clientId,\"] [P2PConnection] receive \").concat(e,\" by exchanging SDP.\"))}else jC.debug(\"[\".concat(this.store.clientId,\"] [P2PConnection] receive \").concat(e,\" no need to exchange SDP.\"));const o=this.peerConnection.getTransceivers().find((e=>e.mid===r));if(!o)throw new Error(\"Cannot get transceiver after setLocalDescription.\");return{track:o.receiver.track,id:r,transceiver:o}}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,\"P2PConnection.receive failed; \".concat(e.toString()))}}async batchReceive(e){try{if(!this.remoteSDP)throw new Error(\"Cannot call P2PConnection.batchReceive before remoteSDP created.\");const{mids:t,needExchangeSDP:i}=this.remoteSDP.batchSend(e);if(i){const e=this.remoteSDP.toString(),t=this.logSDPExchange(e,\"offer\",\"remote\",\"receive\");await this.peerConnection.setRemoteDescription({type:\"offer\",sdp:e});const i=await this.peerConnection.createAnswer();null==t||t(i.sdp||\"\"),await this.peerConnection.setLocalDescription(i),jC.debug(\"[\".concat(this.store.clientId,\"] [P2PConnection] batchReceive by exchanging SDP.\"))}else jC.debug(\"[\".concat(this.store.clientId,\"] [P2PConnection] batchReceive no need to exchange SDP.\"));return t.map((e=>{const t=this.peerConnection.getTransceivers().find((t=>t.mid===e));if(!t)throw new Error(\"Cannot get transceiver after setLocalDescription.\");return{track:t.receiver.track,id:e,transceiver:t}}))}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,\"P2PConnection.receive failed; \".concat(e.toString()))}}async stopReceiving(e){try{if(!this.remoteSDP)throw new Error(\"Cannot call P2PConnection.stopReceiving before remote SDP created.\");this.remoteSDP.stopSending(e);const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,\"offer\",\"remote\",\"stopReceiving\");await this.peerConnection.setRemoteDescription({type:\"offer\",sdp:t});const n=await this.peerConnection.createAnswer();null==i||i(n.sdp||\"\"),await this.peerConnection.setLocalDescription(n)}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,\"P2PConnection stopReceiving failed; \".concat(e.toString()))}}async muteRemote(e){try{if(!this.remoteSDP)throw new Error(\"Cannot call P2PConnection.muteRemote mid=\".concat(e,\" before remote SDP created.\"));this.remoteSDP.mute(e);const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,\"offer\",\"remote\",\"muteRemote\");await this.peerConnection.setRemoteDescription({type:\"offer\",sdp:t});const n=await this.peerConnection.createAnswer();null==i||i(n.sdp||\"\"),await this.peerConnection.setLocalDescription(n)}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,\"P2PConnection.muteRemote failed; \".concat(e.toString()))}}async unmuteRemote(e){try{if(!this.remoteSDP)throw new Error(\"Cannot call P2PConnection.unmuteRemote mid=\".concat(e,\" before remote SDP created.\"));this.remoteSDP.unmute(e);const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,\"offer\",\"remote\",\"unmuteRemote\");await this.peerConnection.setRemoteDescription({type:\"offer\",sdp:t});const n=await this.peerConnection.createAnswer();null==i||i(n.sdp||\"\"),await this.peerConnection.setLocalDescription(n)}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,\"P2PConnection.unmuteRemote failed; \".concat(e.toString()))}}async muteLocal(e){try{if(!this.remoteSDP)throw new Error(\"Cannot call P2PConnection.muteLocal before remote SDP created.\");const t=this.peerConnection.getTransceivers().filter((t=>t.mid&&-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error(\"Transceivers' length doesn't match mids' length.\");t.map((e=>{e.direction=\"inactive\"}));const i=await this.peerConnection.createOffer(),n=this.logSDPExchange(i.sdp||\"\",\"offer\",\"local\",\"muteLocal\");await this.peerConnection.setLocalDescription(i),this.remoteSDP.muteRemote(e);const r=this.remoteSDP.toString();null==n||n(r),await this.peerConnection.setRemoteDescription({type:\"answer\",sdp:r})}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,\"P2PConnection.muteLocal failed; \".concat(e.toString()))}}async unmuteLocal(e){try{if(!this.remoteSDP)throw new Error(\"Cannot call P2PConnection.unmuteLocal before remote SDP created.\");const t=this.peerConnection.getTransceivers().filter((t=>t.mid&&-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error(\"Transceivers' length doesn't match mids' length.\");t.map((async(e,t)=>{e.direction=\"sendonly\"}));const i=await this.peerConnection.createOffer(),n=this.logSDPExchange(i.sdp||\"\",\"offer\",\"local\",\"unmuteLocal\");await this.peerConnection.setLocalDescription(i),this.remoteSDP.unmuteRemote(e);const r=this.remoteSDP.toString();null==n||n(r),await this.peerConnection.setRemoteDescription({type:\"answer\",sdp:r})}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,\"P2PConnection.unmuteLocal failed; \".concat(e.toString()))}}restartICE(e){var t=this;return PU((function*(){const i=yield IU(t.mutex.lock(\"From P2PConnection.restartICE\"));try{if(!t.remoteSDP)throw new Error(\"Cannot restartICE before remoteSDP created.\");if(IA().supportPCSetConfiguration){const i=t.peerConnection.getConfiguration(),n=e===cv.RELAY?\"relay\":\"all\";i.iceTransportPolicy!==n&&(jC.debug(\"[\".concat(t.store.clientId,\"] restartICE change iceTransportPolicy from [\").concat(i.iceTransportPolicy,\"] to [\").concat(n,\"]\")),i.iceTransportPolicy=n,t.peerConnection.setConfiguration(i))}else if(e===cv.RELAY)return;t.remoteSDP.updateCandidates(e);const n=yield IU(t.peerConnection.createOffer({iceRestart:!0}));if(!n.sdp)throw new Error(\"Cannot restartICE because restart offer SDP does not exist.\");const r=Tx(n.sdp),{remoteIceParameters:s}=yield r.iceParameters;t.remoteSDP.restartICE(s);const o=t.remoteSDP.toString(),a=t.logSDPExchange(n.sdp||\"\",\"offer\",\"local\",\"restartICE\");t.store.descriptionStart(),yield IU(t.peerConnection.setLocalDescription(n)),null==a||a(o),yield IU(t.peerConnection.setRemoteDescription({type:\"answer\",sdp:o}))}catch(e){jC.warning(\"[\".concat(t.store.clientId,\"] restart ICE failed, abort operation\"),e)}finally{i()}}))()}close(){var e;this.peerConnection.close(),null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,\"closed\"),this.tryUnbindTransportEvents(),this.unbindPCEvents(),this.unbindStatsEvents(),this.removeAllListeners(),this.transportEventReceiver=void 0,this.statsFilter.destroy(),this.dataStreamChannelMap.clear(),this.recoveredDataChannelIds=[],this.currentDataChannelId=1}getStats(){return this.statsFilter.getStats()}getRemoteVideoIsReady(e){return this.statsFilter.getVideoIsReady(e)}async updateEncoderConfig(e,t){try{if(!this.remoteSDP)throw new Error(\"Cannot call P2PConnection.updateEncoderConfig before remote SDP created.\");const i=await this.peerConnection.createOffer(),n=this.mungSendOfferSDP(i.sdp,[t],[e]);this.remoteSDP.updateRecvMedia(e,t);const r=this.remoteSDP.toString(),s=this.logSDPExchange(n,\"offer\",\"local\",\"updateEncoderConfig\");await this.peerConnection.setLocalDescription({type:\"offer\",sdp:n}),null==s||s(r),await this.peerConnection.setRemoteDescription({type:\"answer\",sdp:r})}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,e.toString())}}async updateSendParameters(e,t){const i=this.peerConnection.getTransceivers().filter((t=>t.mid===e));1===i.length&&(this.isVP8Simulcast(t)?wg()||await this.applySimulcastEncodings(i,[t]):await this.applySendEncodings(i,[t]))}setStatsRemoteVideoIsReady(e,t){this.statsFilter.setVideoIsReady2(e,t)}async replaceTrack(e,t){const i=this.peerConnection.getTransceivers().find((e=>e.mid===t));i&&await i.sender.replaceTrack(e._mediaStreamTrack)}async getSelectedCandidatePair(){const e=this.peerConnection.getReceivers();if(e.length>0&&e[0].transport&&e[0].transport.iceTransport&&e[0].transport.iceTransport.getSelectedCandidatePair&&e[0].transport.iceTransport.getSelectedCandidatePair()){const t=e[0].transport.iceTransport,{local:i,remote:n}=t.getSelectedCandidatePair();return{local:BV(BV({},$U),{},{candidateType:i.type,protocol:i.protocol,address:i.address,port:i.port}),remote:BV(BV({},$U),{},{candidateType:n.type,protocol:n.protocol,address:n.address,port:n.port})}}return this.statsFilter.getSelectedCandidatePair()}bindPCEvents(){this.peerConnection.oniceconnectionstatechange=()=>{var e;null===(e=this.onICEConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.iceConnectionState)},this.peerConnection.onconnectionstatechange=()=>{var e;null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.connectionState)},this.peerConnection.onicecandidate=e=>{e.candidate?this.localCandidateCount+=1:(this.peerConnection.onicecandidate=null,this.allCandidatesReceived=!0,jC.debug(\"[\".concat(this.store.clientId,\"] [pc-\").concat(this.store.p2pId,\"] local candidate count\"),this.localCandidateCount))},setTimeout((()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,jC.debug(\"[\".concat(this.store.clientId,\"] [pc-\").concat(this.store.p2pId,\"] onicecandidate timeout, local candidate count\"),this.localCandidateCount))}),RC(\"CANDIDATE_TIMEOUT\"))}unbindPCEvents(){this.peerConnection.oniceconnectionstatechange=null,this.peerConnection.onconnectionstatechange=null,this.peerConnection.onsignalingstatechange=null,this.peerConnection.onicecandidateerror=null,this.peerConnection.onicecandidate=null,this.peerConnection.ontrack=null}static resolvePCConfiguration(e){const t={iceServers:[]};return e.iceServers?t.iceServers=e.iceServers:e.turnServer&&\"off\"!==e.turnServer.mode&&(RT(e.turnServer.servers)?t.iceServers=e.turnServer.servers:(t.iceServers&&t.iceServers.push(...jV.turnServerConfigToIceServers(e.turnServer.servers)),RC(\"USE_TURN_SERVER_OF_GATEWAY\")&&t.iceServers&&e.turnServer.serversFromGateway&&t.iceServers.push(...jV.turnServerConfigToIceServers(e.turnServer.serversFromGateway)),RC(\"FORCE_TURN_TCP\")?t.iceTransportPolicy=\"relay\":e.turnServer.servers.concat(e.turnServer.serversFromGateway||[]).forEach((e=>{e.forceturn&&(t.iceTransportPolicy=\"relay\")})))),RC(\"ENABLE_ENCODED_TRANSFORM\")&&IA().supportWebRTCEncodedTransform&&(t.encodedInsertableStreams=!0),t}static turnServerConfigToIceServers(e){const t=[];return e.forEach((e=>{e.security?e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:\"password\",urls:\"turns:\".concat(gy(e.turnServerURL),\":\").concat(e.tcpport,\"?transport=tcp\")}):(e.udpport&&!RC(\"FORCE_TURN_TCP\")&&t.push({username:e.username,credential:e.password,credentialType:\"password\",urls:\"turn:\".concat(e.turnServerURL,\":\").concat(e.udpport,\"?transport=udp\")}),e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:\"password\",urls:\"turn:\".concat(e.turnServerURL,\":\").concat(e.tcpport,\"?transport=tcp\")}))})),t}tryBindTransportEvents(e){const t=e.transport;if(t){this.transportEventReceiver=e,t.onstatechange=()=>{var e;null!=t&&t.state&&(null===(e=this.onDTLSTransportStateChange)||void 0===e||e.call(this,t.state))},t.onerror=e=>{var t;null===(t=this.onDTLSTransportError)||void 0===t||t.call(this,\"error\"in e?e.error:e)};const i=t.iceTransport;i&&(i.onstatechange=()=>{const e=null==t?void 0:t.iceTransport.state;var i;e&&(null===(i=this.onICETransportStateChange)||void 0===i||i.call(this,e))},i.getSelectedCandidatePair&&(i.onselectedcandidatepairchange=()=>{if(i.getSelectedCandidatePair()){const{local:e,remote:t}=i.getSelectedCandidatePair();jC.info(\"[\".concat(this.store.clientId,\"] [pc-\").concat(this.store.p2pId,\"] selectedcandidatepairchange: local \").concat(JSON.stringify({candidateType:e.type,protocol:e.protocol}),\", remote \").concat(JSON.stringify({candidateType:t.type,protocol:t.protocol,address:t.address,port:t.port}),\" )\"))}}))}}tryUnbindTransportEvents(){this.transportEventReceiver&&this.transportEventReceiver.transport&&(this.transportEventReceiver.transport.onstatechange=null,this.transportEventReceiver.transport.onerror=null,this.transportEventReceiver.transport.iceTransport&&(this.transportEventReceiver.transport.iceTransport.onstatechange=null))}async updateRtpSenderEncodings(e,t){var i;if(!t){t=this.peerConnection.getSenders().find((t=>t.track===e._mediaStreamTrack))}if(!t)return jC.warn(\"[\".concat(e.getTrackId(),\"] no rtpSender found}\"));if(this.isVP8Simulcast(e))return jC.warn(\"[updateRtpSenderEncodings] Track is VP8 simulcast, please apply simulcast encodings\");if(!IA().supportSetRtpSenderParameters)return jC.warn(\"[updateRtpSenderEncodings] Browser not support set rtp-sender parameters\");const n={},r={};switch(e._optimizationMode){case\"motion\":n.degradationPreference=\"maintain-framerate\";break;case\"detail\":n.degradationPreference=\"maintain-resolution\";break;default:n.degradationPreference=\"balanced\"}if(e._encoderConfig){var s;const{bitrateMax:t,frameRate:i,scaleResolutionDownBy:n}=e._encoderConfig;t&&(r.maxBitrate=1e3*t),(bn(s=e._hints).call(s,jA.LOW_STREAM)||e.isUseScaleResolutionDownBy)&&(i&&(r.maxFramerate=Sy(i)),n&&n>=1&&(r.scaleResolutionDownBy=n))}if(RC(\"DSCP_TYPE\")&&jg()){var o;const e=RC(\"DSCP_TYPE\");bn(o=[\"very-low\",\"low\",\"medium\",\"high\"]).call(o,e)&&(r.networkPriority=e)}const a=t.getParameters(),c=null===(i=a.encodings)||void 0===i?void 0:i[0];wg()&&!c&&(n.encodings=[r]),c&&Object.assign(c,r),Object.assign(a,n),jC.debug(\"[\".concat(e.getTrackId(),\"] updateRtpSenderEncodings: \").concat(JSON.stringify(a.encodings))),await t.setParameters(a)}async applySendEncodings(e,t){try{if(!IA().supportSetRtpSenderParameters)return;if(e.length!==t.length)return;for(let i=0;i{const r=i[t],s=n.mediaDescriptions.find((e=>e.attributes.mid===r));s&&(Ix(s,e),wx(s,e,this.store.codec))})),JU.print(n)}mungReceiveAnswerSDP(e,t,i){const n=JU.parse(e),r=n.mediaDescriptions.find((e=>e.attributes.mid===t));return r&&(i===av.AUDIO&&\"audio\"===r.media.mediaType&&Lx(r),this.useXR&&kx(n)),JU.print(n)}bindStatsEvents(){this.statsFilter.onFirstAudioReceived=e=>{var t;null===(t=this.onFirstAudioReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoReceived=e=>{var t;null===(t=this.onFirstVideoReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstAudioDecoded=e=>{var t;null===(t=this.onFirstAudioDecoded)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoDecoded=(e,t,i)=>{var n;null===(n=this.onFirstVideoDecoded)||void 0===n||n.call(this,e,t,i)},this.statsFilter.onSelectedLocalCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedLocalCandidateChanged)||void 0===i||i.call(this,e,t)},this.statsFilter.onSelectedRemoteCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedRemoteCandidateChanged)||void 0===i||i.call(this,e,t)},this.statsFilter.onFirstVideoDecodedTimeout=e=>{var t;null===(t=this.onFirstVideoDecodedTimeout)||void 0===t||t.call(this,e)}}unbindStatsEvents(){this.statsFilter.onFirstAudioReceived=void 0,this.statsFilter.onFirstVideoReceived=void 0,this.statsFilter.onFirstAudioDecoded=void 0,this.statsFilter.onFirstVideoDecoded=void 0,this.statsFilter.onSelectedLocalCandidateChanged=void 0,this.statsFilter.onSelectedRemoteCandidateChanged=void 0,this.statsFilter.onFirstVideoDecodedTimeout=void 0}async applySimulcastForFirefox(e,t){if(e.length===t.length)for(let a=0;a200&&null!==(s=d._scalabilityMode)&&void 0!==s&&s.numSpatialLayers&&(null===(o=d._scalabilityMode)||void 0===o?void 0:o.numSpatialLayers)>1&&\"vp8\"===this.store.codec){const e={},t={high:1e3*(d._encoderConfig.bitrateMax-50),medium:5e4};e.encodings=[{rid:\"m\",active:!0,maxBitrate:t.medium,scaleResolutionDownBy:4},{rid:\"h\",active:!0,maxBitrate:t.high}];const i=c.sender.getParameters();await c.sender.setParameters(Object.assign(i,e))}}}async applySimulcastEncodings(e,t){if(!wg()&&e.length===t.length)for(let i=0;i200&&null!==(r=e._scalabilityMode)&&void 0!==r&&r.numSpatialLayers&&(null===(s=e._scalabilityMode)||void 0===s?void 0:s.numSpatialLayers)>1)}logSDPExchange(e,t,i,n){if(RC(\"SDP_LOGGING\"))return jC.upload(\"[\".concat(this.store.clientId,\"] exchanging \").concat(i,\" \").concat(t,\" SDP during P2PConnection.\").concat(n,\"\\n\"),e),\"offer\"===t?e=>{this.logSDPExchange(e,\"answer\",\"local\"===i?\"remote\":\"local\",n)}:void 0}async getRemoteSSRC(e){if(!this.remoteSDP)return;const t=this.remoteSDP.getSSRC(e);return null==t?void 0:t[0].ssrcId}setConfiguration(e){if(IA().supportPCSetConfiguration){const t=jV.resolvePCConfiguration(e);this.peerConnection.setConfiguration(t)}}}function GV(e,t,i){const n=e[t];if(\"function\"!=typeof n)throw new Error(\"Cannot use mutex on object property.\");return i.value=async function(){const e=this.mutex,i=await e.lock(\"From P2PConnection.\".concat(t));try{for(var r=arguments.length,s=new Array(r),o=0;oe.payloadType.toString(10))),e.attributes.payloads=d.videoCodecs,e.attributes.extmaps=d.videoExtensions,RC(\"PRELOAD_MEDIA_COUNT\")>0)){const{ssrcs:t,ssrcGroups:i}=Cx([{ssrcId:zV,rtx:RC(\"USE_SUB_RTX\")?40001:void 0}],this.cname);e.attributes.ssrcs=t,e.attributes.ssrcGroups=i}if(\"audio\"===e.media.mediaType&&(e.media.fmts=d.audioCodecs.map((e=>e.payloadType.toString(10))),e.attributes.payloads=d.audioCodecs,e.attributes.extmaps=d.audioExtensions,Lx(e),RC(\"PRELOAD_MEDIA_COUNT\")>0)){const{ssrcs:t,ssrcGroups:i}=Cx([{ssrcId:qV}],this.cname);e.attributes.ssrcs=t,e.attributes.ssrcGroups=i}}this.sessionDesc=c,this.currentMidIndex=c.mediaDescriptions.length-1}updateRemoteRTPCapabilities(e){const t=JU.parse(KV);this._rtpCapabilities=e;const i=this.rtpCapabilities.send;for(const e of t.mediaDescriptions){if(e.attributes.iceUfrag=this._iceParameters.iceUfrag,e.attributes.icePwd=this._iceParameters.icePwd,e.attributes.fingerprints=this._dtlsParameters.fingerprints,e.attributes.candidates=this._candidates,e.attributes.setup=this.setup,\"application\"===e.media.mediaType&&(e.attributes.sctpPort=\"5000\"),\"video\"===e.media.mediaType&&(e.media.fmts=i.videoCodecs.map((e=>e.payloadType.toString(10))),e.attributes.payloads=i.videoCodecs,e.attributes.extmaps=i.videoExtensions,RC(\"PRELOAD_MEDIA_COUNT\")>0)){const{ssrcs:t,ssrcGroups:i}=Cx([{ssrcId:zV,rtx:RC(\"USE_SUB_RTX\")?40001:void 0}],this.cname);e.attributes.ssrcs=t,e.attributes.ssrcGroups=i}if(\"audio\"===e.media.mediaType&&(e.media.fmts=i.audioCodecs.map((e=>e.payloadType.toString(10))),e.attributes.payloads=i.audioCodecs,e.attributes.extmaps=i.audioExtensions,RC(\"PRELOAD_MEDIA_COUNT\")>0)){const{ssrcs:t,ssrcGroups:i}=Cx([{ssrcId:qV}],this.cname);e.attributes.ssrcs=t,e.attributes.ssrcGroups=i}}this.sessionDesc=t,this.currentMidIndex=t.mediaDescriptions.length-1}preloadRemoteMedia(e){this.rtpCapabilities;const t=this.candidates,i=this.dtlsParameters,n=this.iceParameters,r=this.rtpCapabilities.send;for(let s=1;se.payloadType.toString(10)))},connections:[{nettype:\"IN\",addrtype:\"IP4\",address:\"127.0.0.1\"}],bandwidths:[],attributes:{iceUfrag:n.iceUfrag,icePwd:n.icePwd,unrecognized:[],candidates:t,extmaps:r.videoExtensions,fingerprints:i.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:d,ssrcGroups:l,rtcpFeedbackWildcards:[],payloads:r.videoCodecs,rtcp:{port:\"9\",netType:\"IN\",addressType:\"IP4\",address:\"0.0.0.0\"},setup:this.setup,direction:\"sendonly\",rtcpMux:!0,rtcpRsize:!0,mid:\"\".concat(2*s-1)}}),this.sessionDesc.mediaDescriptions.push({media:{mediaType:\"audio\",port:YV,protos:[\"UDP\",\"TLS\",\"RTP\",\"SAVPF\"],fmts:r.audioCodecs.map((e=>e.payloadType.toString(10)))},connections:[{nettype:\"IN\",addrtype:\"IP4\",address:\"127.0.0.1\"}],bandwidths:[],attributes:{iceUfrag:n.iceUfrag,icePwd:n.icePwd,unrecognized:[],candidates:t,extmaps:r.audioExtensions,fingerprints:i.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:a,ssrcGroups:c,rtcpFeedbackWildcards:[],payloads:r.audioCodecs,rtcp:{port:\"9\",netType:\"IN\",addressType:\"IP4\",address:\"0.0.0.0\"},setup:this.setup,direction:\"sendonly\",rtcpMux:!0,rtcpRsize:!0,mid:\"\".concat(2*s)}}),this.currentMidIndex+=2}this.updateBundleMids()}toString(){return JU.print(this.sessionDesc)}send(e,t,i,n){const{ssrcs:r,ssrcGroups:s}=Cx(t,this.cname,RC(\"SYNC_GROUP\")?i:void 0),o=this.findPreloadMediaDesc(r);if(o){if(wg()&&this.firefoxSsrcMidMap.set(r[0].ssrcId,o.attributes.mid),n&&(n.twcc||n.remb)){const e=this.sessionDesc.mediaDescriptions.indexOf(o);return this.sessionDesc.mediaDescriptions[e]=this.mungSendMediaDesc(o,n),{mid:o.attributes.mid,needExchangeSDP:!0}}return{mid:o.attributes.mid,needExchangeSDP:!1}}{const t=this.findAvailableMediaIndex(e,r);let i;return-1===t||bg()||Og()||Lg()||0===t&&RC(\"USE_SUB_RTX\")?(i=this.createOrRecycleSendMedia(e,r,s,\"sendonly\",n),this.updateBundleMids()):(i=YT(this.sessionDesc.mediaDescriptions[t]),i.attributes.direction=\"sendonly\",i.attributes.ssrcs=r,i.attributes.ssrcGroups=s,this.sessionDesc.mediaDescriptions[t]=this.mungSendMediaDesc(i,n)),wg()&&this.firefoxSsrcMidMap.set(r[0].ssrcId,i.attributes.mid),{mid:i.attributes.mid,needExchangeSDP:!0}}}batchSend(e){const t=e.map((e=>{let{kind:t,ssrcMsg:i,mslabel:n}=e;return this.send(t,i,n)})),i=[];let n=!1;return t.forEach((e=>{let{mid:t,needExchangeSDP:r}=e;r&&(n=!0),i.push(t)})),{mids:i,needExchangeSDP:n}}stopSending(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>t.attributes.mid&&-1!==e.indexOf(t.attributes.mid)));if(t.length!==e.length)throw new Error(\"mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.stopSending.\");t.forEach((e=>{\"0\"===e.attributes.mid||wg()||bg()||Og()?e.attributes.ssrcs=[]:(e.attributes.ssrcs=[],e.attributes.direction=\"inactive\",e.media.port=\"0\")})),this.updateBundleMids()}mute(e){const t=this.sessionDesc.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error(\"mediaDescription not found with \".concat(e,\" in remote SDP when calling RemoteSDP.mute.\"));t.attributes.direction=\"inactive\"}unmute(e){const t=this.sessionDesc.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error(\"mediaDescription not found with \".concat(e,\" in remote SDP when calling RemoteSDP.unmute.\"));t.attributes.direction=\"sendonly\"}muteRemote(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>bn(e).call(e,t.attributes.mid||\"\")));if(t.length!==e.length)throw new Error(\"mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.\");t.forEach((e=>{e.attributes.direction=\"inactive\"}))}unmuteRemote(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>bn(e).call(e,t.attributes.mid||\"\")));if(t.length!==e.length)throw new Error(\"mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.\");t.forEach((e=>{e.attributes.direction=\"recvonly\"}))}receive(e,t,i,n){e.forEach(((e,r)=>{this.createOrRecycleRecvMedia(e,[],\"recvonly\",t,i,n[r])})),this.updateBundleMids()}stopReceiving(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>-1!==e.indexOf(t.attributes.mid)));if(t.length!==e.length)throw new Error(\"MediaDescriptions' length doesn't match mids's length when calling RemoteSDP.receive.\");t.forEach((e=>{e.media.port=\"0\",e.attributes.direction=\"inactive\"})),this.updateBundleMids()}updateCandidates(e){e===cv.TCP?this._candidates.forEach((e=>{-1===this._candidates.findIndex((t=>\"tcp\"===t.transport&&t.connectionAddress===e.connectionAddress&&t.port===e.port))&&this._candidates.push(HV(HV({},e),{},{foundation:\"tcpcandidate\",priority:Number(e.priority)-1+\"\",transport:\"tcp\",port:Number(e.port)+90+\"\"}))})):this._candidates=this._candidates.filter((e=>\"tcp\"!==e.transport));for(const e of this.sessionDesc.mediaDescriptions)e.attributes.candidates=this.candidates}restartICE(e){e=YT(e),this._iceParameters=e,this.sessionDesc.mediaDescriptions.forEach((t=>{t.attributes.iceUfrag=e.iceUfrag,t.attributes.icePwd=e.icePwd}))}predictReceivingMids(e){const t=[];for(let i=0;i{const n=i.media.mediaType===e&&\"0\"!==i.media.port&&(\"sendonly\"===i.attributes.direction||\"sendrecv\"===i.attributes.direction)&&0===i.attributes.ssrcs.length;if(wg()){if(n){const e=this.firefoxSsrcMidMap.get(t[0].ssrcId);return!(e||\"0\"!==i.attributes.mid&&\"1\"!==i.attributes.mid)||!(!e||e!==i.attributes.mid)}return!1}return n}))}createOrRecycleRecvMedia(e,t,i,n,r,s){const o=e._mediaStreamTrack.kind,a=this.rtpCapabilities.recv,c=Mx(o,a,this.localCapabilities.send,o===av.VIDEO?n:r),d=o===av.VIDEO?a.videoExtensions:a.audioExtensions;this.currentMidIndex+=1;const l=\"\".concat(this.currentMidIndex);let u={media:{mediaType:o,port:YV,protos:[\"UDP\",\"TLS\",\"RTP\",\"SAVPF\"],fmts:c.map((e=>e.payloadType.toString(10)))},connections:[{nettype:\"IN\",addrtype:\"IP4\",address:\"127.0.0.1\"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:this.candidates,extmaps:d,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:c,rtcp:{port:\"9\",netType:\"IN\",addressType:\"IP4\",address:\"0.0.0.0\"},setup:this.setup,direction:i,rtcpMux:!0,rtcpRsize:!0,mid:\"\".concat(l)}};u=this.mungRecvMediaDsec(u,e,s);const h=this.findFirstClosedMedia(o);if(h){const e=this.sessionDesc.mediaDescriptions.indexOf(h);this.sessionDesc.mediaDescriptions[e]=u}else this.sessionDesc.mediaDescriptions.push(u);return u}updateRemoteCodec(e,t,i){const n=[...new Set(this._rtpCapabilities.recv.videoCodecs.map((e=>e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||\"\")).filter((e=>{var t;return bn(t=Object.keys(bC)).call(t,e)})))],r=new Set(t);if(n.every((e=>r.has(e))))return jC.debug(\"codecs has not changed, no need to updateRemoteCodec, codecs: \".concat(t)),!1;const s=this._rtpCapabilities.recv.videoCodecs.filter((e=>t.some((t=>{var i;return bn(i=e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||\"\").call(i,t)}))));if(0===s.length)return jC.debug(\"updateRemoteCodec failed, because cannot find matched codec, remoteCapabilities codecs: \".concat(n,\" codecs: \").concat(t)),!1;const o=[...new Set(s.map((e=>e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||\"\")))];let a;if(jC.debug(\"updateRemoteCodec, from \".concat(n,\" to \").concat(o)),0===e.length)a=this.sessionDesc.mediaDescriptions.filter((e=>\"video\"===e.media.mediaType&&\"recvonly\"===e.attributes.direction));else if(a=this.sessionDesc.mediaDescriptions.filter((t=>t.attributes.mid&&bn(e).call(e,t.attributes.mid)&&\"recvonly\"===t.attributes.direction)),a.length!==e.length)return jC.debug(\"updateRemoteCodec failed, because cannot find mids, mids: \".concat(e,\", codecs: \").concat(t)),!1;this._rtpCapabilities.recv.videoCodecs=s;const c=this.localCapabilities.send,d=this.rtpCapabilities.recv,l=Mx(av.VIDEO,d,c,i);return a.forEach((e=>{const t=l.map((e=>e.payloadType.toString(10)));jC.debug(\"updateRemoteCodec mid: \".concat(e.attributes.mid,\", from \").concat(e.attributes.payloads,\" to \").concat(l)),e.attributes.payloads=l,e.media.fmts=t})),!0}createOrRecycleSendMedia(e,t,i,n,r){const s=this.rtpCapabilities.send,o=e===av.VIDEO?s.videoCodecs:s.audioCodecs,a=e===av.VIDEO?s.videoExtensions:s.audioExtensions;this.currentMidIndex+=1;const c=\"\".concat(this.currentMidIndex);let d={media:{mediaType:e,port:YV,protos:[\"UDP\",\"TLS\",\"RTP\",\"SAVPF\"],fmts:o.map((e=>e.payloadType.toString(10)))},connections:[{nettype:\"IN\",addrtype:\"IP4\",address:\"127.0.0.1\"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:this.candidates,extmaps:a,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:i,rtcpFeedbackWildcards:[],payloads:o,rtcp:{port:\"9\",netType:\"IN\",addressType:\"IP4\",address:\"0.0.0.0\"},setup:this.setup,direction:n,rtcpMux:!0,rtcpRsize:!0,mid:\"\".concat(c)}};d=this.mungSendMediaDesc(d,r);const l=this.findFirstClosedMedia(e);if(l){const e=this.sessionDesc.mediaDescriptions.indexOf(l);this.sessionDesc.mediaDescriptions[e]=d}else this.sessionDesc.mediaDescriptions.push(d);return d}updateBundleMids(){this.sessionDesc.attributes.groups[0].identificationTag=this.sessionDesc.mediaDescriptions.filter((e=>\"0\"!==e.media.port)).map((e=>e.attributes.mid))}mungRecvMediaDsec(e,t,i){const n=YT(e);return vx(n),Ix(n,t),yx(n,t),Ax(n),bx(n,i,this.localCapabilities.send),n}mungSendMediaDesc(e,t){const i=YT(e);return bx(i,t,this.localCapabilities.recv),Lx(i),i}updateRecvMedia(e,t){const i=this.sessionDesc.mediaDescriptions.findIndex((t=>t.attributes.mid===e));if(-1!==i){const e=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[i],t);this.sessionDesc.mediaDescriptions[i]=e}}bumpMid(e){this.currentMidIndex+=e}findFirstClosedMedia(e){return this.sessionDesc.mediaDescriptions.find((t=>wg()?\"0\"===t.media.port&&t.media.mediaType===e:\"0\"===t.media.port))}findPreloadMediaDesc(e){return this.sessionDesc.mediaDescriptions.find((t=>{var i;return(null===(i=t.attributes)||void 0===i||null===(i=i.ssrcs[0])||void 0===i?void 0:i.ssrcId)===e[0].ssrcId}))}getSSRC(e){var t;return null===(t=this.sessionDesc.mediaDescriptions.find((t=>t.attributes.mid===e)))||void 0===t?void 0:t.attributes.ssrcs}}function XV(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function QV(e){for(var t=1;te.rtpMap&&e.rtpMap.encodingName.toLowerCase()||\"\")).filter((e=>{var t;return bn(t=Object.keys(bC)).call(t,e)})))]}constructor(e,t,i){super(e,t),sh(this,\"store\",void 0),sh(this,\"peerConnection\",void 0),sh(this,\"remoteSDP\",void 0),sh(this,\"initialOffer\",void 0),sh(this,\"transportEventReceiver\",void 0),sh(this,\"statsFilter\",void 0),sh(this,\"useXR\",RC(\"USE_XR\")),sh(this,\"localCapabilities\",void 0),sh(this,\"localCandidateCount\",0),sh(this,\"allCandidatesReceived\",!1),sh(this,\"remoteCodecs\",void 0),sh(this,\"dataStreamChannelMap\",new Map),sh(this,\"establishPromise\",void 0),sh(this,\"mutex\",new pS(\"NVExtentionsConnection-mutex\")),sh(this,\"rtcMedia\",void 0),this.store=t,this.peerConnection=i,this.statsFilter=Ex(this.peerConnection,RC(\"STATS_UPDATE_INTERVAL\"),void 0,wg()?1200:void 0),this.bindPCEvents(),this.bindStatsEvents(),this.store.p2pId=this.store.p2pId+1,this.establishPromise=this.establish()}async establish(e){try{const e=await this.peerConnection.createOffer();if(!e.sdp)throw new Error(\"Cannot get initialOffer.sdp when trying to establish PeerConnection.\");const t=Tx(e.sdp),i=await Ox({filterRTX:!RC(\"USE_PUB_RTX\")&&!RC(\"USE_SUB_RTX\"),filterVideoFec:RC(\"FILTER_VIDEO_FEC\"),filterAudioFec:RC(\"FILTER_AUDIO_FEC\"),filterVideoCodec:RC(\"FILTER_VIDEO_CODEC\")},{useXR:this.useXR});return this.localCapabilities=i,this.initialOffer=e,QV(QV({},t),{},{rtpCapabilities:i,offerSDP:e.sdp})}catch(e){throw new LI(Hg.GET_LOCAL_CONNECTION_PARAMS_FAILED,e.toString())}}async connect(e,t,i,n,r,s){try{if(!this.initialOffer)throw new Error(\"Cannot establish NVConnection without initial offer.\");this.remoteSDP=new JV({remoteIceParameters:e,remoteDtlsParameters:t,candidates:i,remoteRTPCapabilities:n,remoteSetup:r,localCapabilities:Px(this.localCapabilities),cname:s});const o=this.remoteSDP.toString(),a=JU.parse(this.initialOffer.sdp),c=a.mediaDescriptions.find((e=>\"audio\"===e.media.mediaType));c&&Lx(c),this.useXR&&kx(a);const d=JU.print(a),l=this.logSDPExchange(d||\"\",\"offer\",\"local\",\"connect\");await this.peerConnection.setLocalDescription({type:\"offer\",sdp:d}),null==l||l(o),await this.peerConnection.setRemoteDescription({type:\"answer\",sdp:o})}catch(e){throw new LI(Hg.EXCHANGE_SDP_FAILED,\"NV.connect failed; \".concat(e.toString()))}}async updateRemoteRTPCapabilities(e,t){if(this.remoteCodecs=t,!this.remoteSDP)return void jC.debug(\"[P2PConnection] cannot updateRemoteRTPCapabilities before remote SDP created, local codecs: \".concat(this.localCodecs,\", codecs: \").concat(t));if(this.remoteSDP.updateRemoteCodec(e,t,this.store.codec)){const e=await this.peerConnection.createOffer(),t=this.logSDPExchange(e.sdp||\"\",\"offer\",\"local\",\"muteLocal\");await this.peerConnection.setLocalDescription(e);const i=this.remoteSDP.toString();null==t||t(i),await this.peerConnection.setRemoteDescription({type:\"answer\",sdp:i})}else jC.debug(\"[P2PConnection] updateRemoteRTPCapabilities no need to exchange SDP.\")}async updateRemoteConnect(e){var t,i,n,r;(null===(t=this.remoteSDP)||void 0===t||t.updateRemoteRTPCapabilities(e),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0)&&(null===(r=this.remoteSDP)||void 0===r||r.updateRemoteCodec([],this.remoteCodecs,this.store.codec));null===(i=this.remoteSDP)||void 0===i||i.preloadRemoteMedia(2);const s=null===(n=this.remoteSDP)||void 0===n?void 0:n.toString();await this.peerConnection.setRemoteDescription({type:\"offer\",sdp:s});const o=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(o),jC.debug(\"[NVExtentionsConnection] updateRemoteRTPCapabilities by exchanging SDP.\")}send(e,t,i){var n=this;return PU((function*(){const r=yield IU(n.mutex.lock(\"From NVExtentionsConnection.send\"));try{if(!n.remoteSDP)throw new Error(\"Cannot call NVExtentionsConnection.send before remote SDP created\");const s=[];e.forEach((e=>{const t=n.peerConnection.addTransceiver(e._mediaStreamTrack,{direction:\"sendonly\"});s.push(t)})),wg()&&!0===RC(\"SIMULCAST\")&&(yield IU(n.applySimulcastForFirefox(s,e)));const o=yield IU(n.peerConnection.createOffer()),a=n.remoteSDP.predictReceivingMids(e.length),c=n.mungSendOfferSDP(o.sdp,e,a),d=JU.parse(c),l=a.map((e=>{const t=d.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error(\"Cannot extract ssrc from mediaDescription.\");return Sx(t,RC(\"USE_PUB_RTX\"))}));let u;try{u=yield l}catch(r){u=[],n.remoteSDP.receive(e,t,i,u);const s=n.remoteSDP.toString();throw yield IU(n.peerConnection.setLocalDescription({type:\"offer\",sdp:c})),yield IU(n.peerConnection.setRemoteDescription({type:\"answer\",sdp:s})),yield IU(n.stopSending(a,!0)),r}n.remoteSDP.receive(e,t,i,u);const h=n.remoteSDP.toString(),p=n.logSDPExchange(c,\"offer\",\"local\",\"send\");return yield IU(n.peerConnection.setLocalDescription({type:\"offer\",sdp:c})),yield IU(n.applySimulcastEncodings(s,e)),yield IU(n.applySendEncodings(s,e)),null==p||p(h),yield IU(n.peerConnection.setRemoteDescription({type:\"answer\",sdp:h})),s.map(((e,t)=>{const i=a[t];return{localSSRC:l[t],id:i,transceiver:e}}))}catch(e){throw e instanceof LI?e:new LI(Hg.EXCHANGE_SDP_FAILED,\"NVExtentionsConnection.send failed; \".concat(e.toString()))}finally{r()}}))()}async stopSending(e,t){const i=t?void 0:await this.mutex.lock(\"From NVExtentionsConnection.stopSending\");try{if(!this.remoteSDP)throw new Error(\"Cannot call NVExtentionsConnection.stopSending before remote SDP created\");const t=this.peerConnection.getTransceivers().filter((t=>-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error(\"Transceivers' length doesn't match mids' length when trying to call NVExtentionsConnection.stopSending.\");t.map((e=>{var t;e.direction=\"inactive\",null===(t=e.stop)||void 0===t||t.call(e)}));const n=await this.peerConnection.createOffer(),r=this.logSDPExchange(n.sdp||\"\",\"offer\",\"local\",\"stopSending\");await this.peerConnection.setLocalDescription(n),this.remoteSDP.stopReceiving(e);const s=this.remoteSDP.toString();null==r||r(s),await this.peerConnection.setRemoteDescription({type:\"answer\",sdp:s})}catch(e){throw new LI(Hg.EXCHANGE_SDP_FAILED,\"NVExtentionsConnection.stopSending failed; \".concat(e.toString()))}finally{i&&i()}}async createDataChannels(e,t){try{if(!this.remoteSDP)throw new Error(\"Cannot call NVExtentionsConnection.createDataChannels before remote SDP created\");let i=this.dataStreamChannelMap.get(e);return i&&\"open\"===i.readyState?jC.debug(\"[P2PConnection] Channels are already available and can be reused directly.\"):(i=this.peerConnection.createDataChannel(\"datastream-channel\",{ordered:!1,maxRetransmits:RC(\"DATASTREAM_MAX_RETRANSMITS\")}),i.binaryType=\"arraybuffer\",this.dataStreamChannelMap.set(e,i)),void t.forEach((e=>{e._updateOriginDataChannel(i)}))}catch(e){throw e instanceof LI?e:new LI(Hg.DATACHANNEL_FAILED,\"NVExtentionsConnection.createDataChannels failed; \".concat(e.toString()))}}async stopDataChannels(e){try{const t=this.dataStreamChannelMap.get(e);return null==t||t.close(),void this.dataStreamChannelMap.delete(e)}catch(e){throw e instanceof LI?e:new LI(Hg.DATACHANNEL_FAILED,\"NVExtentionsConnection.stopDataChannels failed; \".concat(e.toString()))}}async receive(e,t,i,n){try{if(!this.remoteSDP)throw new Error(\"Cannot call NVExtentionsConnection.receive \".concat(e,\" before remoteSDP created.\"));const{mid:r,needExchangeSDP:s}=this.remoteSDP.send(e,t,i,n);if(s){const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,\"offer\",\"remote\",\"receive\");await this.peerConnection.setRemoteDescription({type:\"offer\",sdp:t});const n=await this.peerConnection.createAnswer(),s=this.mungReceiveAnswerSDP(n.sdp,r,e);null==i||i(s||\"\"),await this.peerConnection.setLocalDescription({type:\"answer\",sdp:s}),jC.debug(\"[NVExtentionsConnection] receive \".concat(e,\" by exchanging SDP.\"))}else jC.debug(\"[NVExtentionsConnection] receive \".concat(e,\" no need to exchange SDP.\"));const o=this.peerConnection.getTransceivers().find((e=>e.mid===r));if(!o)throw new Error(\"Cannot get transceiver after setLocalDescription.\");return{track:o.receiver.track,id:r}}catch(e){throw new LI(Hg.EXCHANGE_SDP_FAILED,\"NVExtentionsConnection.receive failed; \".concat(e.toString()))}}async batchReceive(e){try{if(!this.remoteSDP)throw new Error(\"Cannot call NVExtentionsConnection.batchReceive before remoteSDP created.\");const{mids:t,needExchangeSDP:i}=this.remoteSDP.batchSend(e);if(i){const e=this.remoteSDP.toString(),t=this.logSDPExchange(e,\"offer\",\"remote\",\"receive\");await this.peerConnection.setRemoteDescription({type:\"offer\",sdp:e});const i=await this.peerConnection.createAnswer();null==t||t(i.sdp||\"\"),await this.peerConnection.setLocalDescription(i),jC.debug(\"[NVExtentionsConnection] batchReceive by exchanging SDP.\")}else jC.debug(\"[NVExtentionsConnection] batchReceive no need to exchange SDP.\");return t.map((e=>{const t=this.peerConnection.getTransceivers().find((t=>t.mid===e));if(!t)throw new Error(\"Cannot get transceiver after setLocalDescription.\");return{track:t.receiver.track,id:e}}))}catch(e){throw new LI(Hg.EXCHANGE_SDP_FAILED,\"NVExtentionsConnection.receive failed; \".concat(e.toString()))}}async stopReceiving(e){try{if(!this.remoteSDP)throw new Error(\"Cannot call NVExtentionsConnection.stopReceiving before remote SDP created.\");this.remoteSDP.stopSending(e);const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,\"offer\",\"remote\",\"stopReceiving\");await this.peerConnection.setRemoteDescription({type:\"offer\",sdp:t});const n=await this.peerConnection.createAnswer();null==i||i(n.sdp||\"\"),await this.peerConnection.setLocalDescription(n)}catch(e){throw new LI(Hg.EXCHANGE_SDP_FAILED,\"NVExtentionsConnection stopReceiving failed; \".concat(e.toString()))}}async muteRemote(e){try{if(!this.remoteSDP)throw new Error(\"Cannot call NVExtentionsConnection.muteRemote mid=\".concat(e,\" before remote SDP created.\"));this.remoteSDP.mute(e);const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,\"offer\",\"remote\",\"muteRemote\");await this.peerConnection.setRemoteDescription({type:\"offer\",sdp:t});const n=await this.peerConnection.createAnswer();null==i||i(n.sdp||\"\"),await this.peerConnection.setLocalDescription(n)}catch(e){throw new LI(Hg.EXCHANGE_SDP_FAILED,\"NVExtentionsConnection.muteRemote failed; \".concat(e.toString()))}}async unmuteRemote(e){try{if(!this.remoteSDP)throw new Error(\"Cannot call NVExtentionsConnection.unmuteRemote mid=\".concat(e,\" before remote SDP created.\"));this.remoteSDP.unmute(e);const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,\"offer\",\"remote\",\"unmuteRemote\");await this.peerConnection.setRemoteDescription({type:\"offer\",sdp:t});const n=await this.peerConnection.createAnswer();null==i||i(n.sdp||\"\"),await this.peerConnection.setLocalDescription(n)}catch(e){throw new LI(Hg.EXCHANGE_SDP_FAILED,\"NVExtentionsConnection.unmuteRemote failed; \".concat(e.toString()))}}async muteLocal(e){try{if(!this.remoteSDP)throw new Error(\"Cannot call NVExtentionsConnection.muteLocal before remote SDP created.\");const t=this.peerConnection.getTransceivers().filter((t=>t.mid&&-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error(\"Transceivers' length doesn't match mids' length.\");t.map((e=>{e.direction=\"inactive\"}));const i=await this.peerConnection.createOffer(),n=this.logSDPExchange(i.sdp||\"\",\"offer\",\"local\",\"muteLocal\");await this.peerConnection.setLocalDescription(i),this.remoteSDP.muteRemote(e);const r=this.remoteSDP.toString();null==n||n(r),await this.peerConnection.setRemoteDescription({type:\"answer\",sdp:r})}catch(e){throw new LI(Hg.EXCHANGE_SDP_FAILED,\"NVExtentionsConnection.muteLocal failed; \".concat(e.toString()))}}async unmuteLocal(e){try{if(!this.remoteSDP)throw new Error(\"Cannot call NVExtentionsConnection.unmuteLocal before remote SDP created.\");const t=this.peerConnection.getTransceivers().filter((t=>t.mid&&-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error(\"Transceivers' length doesn't match mids' length.\");t.map((async(e,t)=>{e.direction=\"sendonly\"}));const i=await this.peerConnection.createOffer(),n=this.logSDPExchange(i.sdp||\"\",\"offer\",\"local\",\"unmuteLocal\");await this.peerConnection.setLocalDescription(i),this.remoteSDP.unmuteRemote(e);const r=this.remoteSDP.toString();null==n||n(r),await this.peerConnection.setRemoteDescription({type:\"answer\",sdp:r})}catch(e){throw new LI(Hg.EXCHANGE_SDP_FAILED,\"NVExtentionsConnection.unmuteLocal failed; \".concat(e.toString()))}}restartICE(e){var t=this;return PU((function*(){const i=yield IU(t.mutex.lock(\"From NVExtentionsConnection.restartICE\"));try{if(!t.remoteSDP)throw new Error(\"Cannot restartICE before remoteSDP created.\");if(IA().supportPCSetConfiguration){const i=t.peerConnection.getConfiguration(),n=e===cv.RELAY?\"relay\":\"all\";i.iceTransportPolicy!==n&&(jC.debug(\"restartICE change iceTransportPolicy from [\".concat(i.iceTransportPolicy,\"] to [\").concat(n,\"]\")),i.iceTransportPolicy=n,t.peerConnection.setConfiguration(i))}else if(e===cv.RELAY)return;e!==cv.RELAY&&t.remoteSDP.updateCandidates(e);const n=yield IU(t.peerConnection.createOffer({iceRestart:!0}));if(!n.sdp)throw new Error(\"Cannot restartICE because restart offer SDP does not exist.\");const r=Tx(n.sdp),{remoteIceParameters:s}=yield r.iceParameters;t.remoteSDP.restartICE(s);const o=t.remoteSDP.toString(),a=t.logSDPExchange(n.sdp||\"\",\"offer\",\"local\",\"restartICE\");yield IU(t.peerConnection.setLocalDescription(n)),null==a||a(o),yield IU(t.peerConnection.setRemoteDescription({type:\"answer\",sdp:o}))}catch(e){jC.warning(\"restart ICE failed, abort operation\",e)}finally{i()}}))()}close(){var e;null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,\"closed\"),this.unbindPCEvents(),this.unbindStatsEvents(),this.removeAllListeners(),this.transportEventReceiver=void 0,this.statsFilter.destroy(),this.dataStreamChannelMap.clear()}getStats(){return this.statsFilter.getStats()}getRemoteVideoIsReady(e){return this.statsFilter.getVideoIsReady(e)}async updateEncoderConfig(e,t){try{if(!this.remoteSDP)throw new Error(\"Cannot call NVExtentionsConnection.updateEncoderConfig before remote SDP created.\");const i=await this.peerConnection.createOffer(),n=this.mungSendOfferSDP(i.sdp,[t],[e]);this.remoteSDP.updateRecvMedia(e,t);const r=this.remoteSDP.toString(),s=this.logSDPExchange(n,\"offer\",\"local\",\"updateEncoderConfig\");await this.peerConnection.setLocalDescription({type:\"offer\",sdp:n}),null==s||s(r),await this.peerConnection.setRemoteDescription({type:\"answer\",sdp:r})}catch(e){throw new LI(Hg.EXCHANGE_SDP_FAILED,e.toString())}}async updateSendParameters(e,t){const i=this.peerConnection.getTransceivers().filter((t=>t.mid===e));1===i.length&&(this.isVP8Simulcast(t)?wg()||await this.applySimulcastEncodings(i,[t]):await this.applySendEncodings(i,[t]))}setStatsRemoteVideoIsReady(e,t){this.statsFilter.setVideoIsReady2(e,t)}async replaceTrack(e,t){const i=this.peerConnection.getTransceivers().find((e=>e.mid===t));i&&await i.sender.replaceTrack(e._mediaStreamTrack)}getP2PConnectionParams(){var e;if(null===(e=this.peerConnection.currentLocalDescription)||void 0===e||!e.sdp||!this.localCapabilities)throw new Error;return QV(QV({},Tx(this.peerConnection.currentLocalDescription.sdp)),{},{rtpCapabilities:this.localCapabilities})}bindPCEvents(){this.peerConnection.oniceconnectionstatechange=()=>{var e;null===(e=this.onICEConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.iceConnectionState)},this.peerConnection.onconnectionstatechange=()=>{var e;null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.connectionState)},this.peerConnection.onicecandidate=e=>{e.candidate?this.localCandidateCount+=1:(this.peerConnection.onicecandidate=null,this.allCandidatesReceived=!0,jC.debug(\"[pc-\".concat(this.store.p2pId,\"] local candidate count\"),this.localCandidateCount))},setTimeout((()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,jC.debug(\"[pc-\".concat(this.store.p2pId,\"] onicecandidate timeout, local candidate count\"),this.localCandidateCount))}),RC(\"CANDIDATE_TIMEOUT\"))}unbindPCEvents(){this.peerConnection.oniceconnectionstatechange=null,this.peerConnection.onconnectionstatechange=null,this.peerConnection.onsignalingstatechange=null,this.peerConnection.onicecandidateerror=null,this.peerConnection.onicecandidate=null,this.peerConnection.ontrack=null}static resolvePCConfiguration(e){const t={iceServers:[]};return e.iceServers?t.iceServers=e.iceServers:e.turnServer&&\"off\"!==e.turnServer.mode&&(RT(e.turnServer.servers)?t.iceServers=e.turnServer.servers:(t.iceServers&&t.iceServers.push(...ZV.turnServerConfigToIceServers(e.turnServer.servers)),RC(\"USE_TURN_SERVER_OF_GATEWAY\")&&t.iceServers&&e.turnServer.serversFromGateway&&t.iceServers.push(...ZV.turnServerConfigToIceServers(e.turnServer.serversFromGateway)),RC(\"FORCE_TURN_TCP\")?t.iceTransportPolicy=\"relay\":e.turnServer.servers.concat(e.turnServer.serversFromGateway||[]).forEach((e=>{e.forceturn&&(t.iceTransportPolicy=\"relay\")})))),t}static turnServerConfigToIceServers(e){const t=[];return e.forEach((e=>{e.security?e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:\"password\",urls:\"turns:\".concat(gy(e.turnServerURL),\":\").concat(e.tcpport,\"?transport=tcp\")}):(e.udpport&&!RC(\"FORCE_TURN_TCP\")&&t.push({username:e.username,credential:e.password,credentialType:\"password\",urls:\"turn:\".concat(e.turnServerURL,\":\").concat(e.udpport,\"?transport=udp\")}),e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:\"password\",urls:\"turn:\".concat(e.turnServerURL,\":\").concat(e.tcpport,\"?transport=tcp\")}))})),t}async applySendEncodings(e,t){try{if(!IA().supportSetRtpSenderParameters)return;if(e.length!==t.length)return;for(let l=0;l1&&(t.scaleResolutionDownBy=h._encoderConfig.scaleResolutionDownBy);if(RC(\"DSCP_TYPE\")&&jg()){var d;const e=RC(\"DSCP_TYPE\");bn(d=[\"very-low\",\"low\",\"medium\",\"high\"]).call(d,e)&&(t.networkPriority=e)}const l=u.sender.getParameters(),p=null===(r=l.encodings)||void 0===r?void 0:r[0];wg()&&!p&&(e.encodings=[t]),p&&Object.assign(p,t),Object.assign(l,e),await u.sender.setParameters(l)}}}catch(e){jC.debug(\"Apply RTPSendEncodings failed.\")}}mungSendOfferSDP(e,t,i){const n=JU.parse(e);return t.forEach(((e,t)=>{const r=i[t],s=n.mediaDescriptions.find((e=>e.attributes.mid===r));s&&(Ix(s,e),wx(s,e,this.store.codec))})),JU.print(n)}mungReceiveAnswerSDP(e,t,i){const n=JU.parse(e),r=n.mediaDescriptions.find((e=>e.attributes.mid===t));return r&&i===av.AUDIO&&\"audio\"===r.media.mediaType&&Lx(r),this.useXR&&kx(n),JU.print(n)}bindStatsEvents(){this.statsFilter.onFirstAudioReceived=e=>{var t;null===(t=this.onFirstAudioReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoReceived=e=>{var t;null===(t=this.onFirstVideoReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstAudioDecoded=e=>{var t;null===(t=this.onFirstAudioDecoded)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoDecoded=(e,t,i)=>{var n;null===(n=this.onFirstVideoDecoded)||void 0===n||n.call(this,e,t,i)},this.statsFilter.onSelectedLocalCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedLocalCandidateChanged)||void 0===i||i.call(this,e,t)},this.statsFilter.onSelectedRemoteCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedRemoteCandidateChanged)||void 0===i||i.call(this,e,t)},this.statsFilter.onFirstVideoDecodedTimeout=e=>{var t;null===(t=this.onFirstVideoDecodedTimeout)||void 0===t||t.call(this,e)}}unbindStatsEvents(){this.statsFilter.onFirstAudioReceived=void 0,this.statsFilter.onFirstVideoReceived=void 0,this.statsFilter.onFirstAudioDecoded=void 0,this.statsFilter.onFirstVideoDecoded=void 0,this.statsFilter.onSelectedLocalCandidateChanged=void 0,this.statsFilter.onSelectedRemoteCandidateChanged=void 0,this.statsFilter.onFirstVideoDecodedTimeout=void 0}async applySimulcastForFirefox(e,t){if(e.length===t.length)for(let a=0;a200&&null!==(s=d._scalabilityMode)&&void 0!==s&&s.numSpatialLayers&&(null===(o=d._scalabilityMode)||void 0===o?void 0:o.numSpatialLayers)>1&&\"vp8\"===this.store.codec){const e={},t={high:1e3*(d._encoderConfig.bitrateMax-50),medium:5e4};e.encodings=[{rid:\"m\",active:!0,maxBitrate:t.medium,scaleResolutionDownBy:4},{rid:\"h\",active:!0,maxBitrate:t.high}];const i=c.sender.getParameters();await c.sender.setParameters(Object.assign(i,e))}}}async applySimulcastEncodings(e,t){if(!wg()&&e.length===t.length)for(let i=0;i200&&null!==(r=e._scalabilityMode)&&void 0!==r&&r.numSpatialLayers&&(null===(s=e._scalabilityMode)||void 0===s?void 0:s.numSpatialLayers)>1)}logSDPExchange(e,t,i,n){if(RC(\"SDP_LOGGING\"))return jC.upload(\"exchanging \".concat(i,\" \").concat(t,\" SDP during NVExtentionsConnection.\").concat(n,\"\\n\"),e),\"offer\"===t?e=>{this.logSDPExchange(e,\"answer\",\"local\"===i?\"remote\":\"local\",n)}:void 0}async getRemoteSSRC(e){if(!this.remoteSDP)return;const t=this.remoteSDP.getSSRC(e);return null==t?void 0:t[0].ssrcId}setConfiguration(e){if(IA().supportPCSetConfiguration){const t=ZV.resolvePCConfiguration(e);this.peerConnection.setConfiguration(t)}}}function $V(e,t,i){const n=e[t];if(\"function\"!=typeof n)throw new Error(\"Cannot use mutex on object property.\");return i.value=async function(){const e=this.mutex,i=await e.lock(\"From NVExtentionsConnection.\".concat(t));try{for(var r=arguments.length,s=new Array(r),o=0;o{const n=setTimeout((()=>{this.closeSignal(),t(new LI(Hg.DATACHANNEL_CONNECTION_TIMEOUT,\"Datachannel connection timed out, candidates: \".concat(JSON.stringify(i))))}),2e3);this.dataChannel.onopen=()=>{if(\"open\"===this.dataChannel.readyState)return clearTimeout(n),void e()},this.dataChannel.onerror=e=>{this.closeSignal(),t(e)}})),{transmitter:this.dataChannel,close:this.closeSignal.bind(this)}}async updateRemoteRTPCapabilities(e,t){return this._p2pConnection.updateRemoteRTPCapabilities(e,t)}send(e,t,i){var n=this;return PU((function*(){const r=yield IU(n.mutex.lock(\"From DataChannelConnection.send\"));try{return yield*bV(eF(n._p2pConnection.send(e,t,i)))}finally{r()}}))()}async stopSending(e,t){return this._p2pConnection.stopSending(e,t)}async createDataChannels(e,t){return this._p2pConnection.createDataChannels(e,t)}async stopDataChannels(e){return this._p2pConnection.stopDataChannels(e)}async receive(e,t,i,n){return this._nvMedia?(jC.debug(\"[DataChannelConnection] receive \".concat(e,\" by DataChannel.\")),await this._nvMedia.reveiveByRTCMedia(e,t,this.cname)):(jC.debug(\"[DataChannelConnection] receive \".concat(e,\" by WebRTC.\")),await this._p2pConnection.receive(e,t,i,n))}async batchReceive(e){return[...await this._p2pConnection.batchReceive(e)]}async stopReceiving(e){return await this._p2pConnection.stopReceiving(e)}async muteRemote(e){return await this._p2pConnection.muteRemote(e)}async unmuteRemote(e){return await this._p2pConnection.unmuteRemote(e)}async muteLocal(e){return await this._p2pConnection.muteLocal(e)}async unmuteLocal(e){return await this._p2pConnection.unmuteLocal(e)}restartICE(e){var t=this;return PU((function*(){return yield*bV(eF(t._p2pConnection.restartICE(e)))}))()}close(){var e;null===(e=this._nvMedia)||void 0===e||e.close(),this._p2pConnection.close(),this.unbindConnectionEvents(this._p2pConnection)}getStats(){return this._p2pConnection.getStats()}getRemoteVideoIsReady(e){return this._p2pConnection.getRemoteVideoIsReady(e)}updateRemoteConnect(e){var t;null===(t=this._nvMedia)||void 0===t||t.setRemoteRtpCapabilities(e),this._p2pConnection.updateRemoteConnect(e)}async updateEncoderConfig(e,t){return await this._p2pConnection.updateEncoderConfig(e,t)}async updateSendParameters(e,t){return await this._p2pConnection.updateSendParameters(e,t)}setStatsRemoteVideoIsReady(e,t){this._p2pConnection.setStatsRemoteVideoIsReady(e,t)}async replaceTrack(e,t){return await this._p2pConnection.replaceTrack(e,t)}async getRemoteSSRC(e){return this._p2pConnection.getRemoteSSRC(e)}logSDPExchange(e,t,i,n){if(RC(\"SDP_LOGGING\"))return jC.upload(\"exchanging \".concat(i,\" \").concat(t,\" SDP during DataChannelConnection.\").concat(n,\"\\n\"),e),\"offer\"===t?e=>{this.logSDPExchange(e,\"answer\",\"local\"===i?\"remote\":\"local\",n)}:void 0}static resolvePCConfiguration(e){const t={iceServers:[]};return e.iceServers?t.iceServers=e.iceServers:e.turnServer&&\"off\"!==e.turnServer.mode&&(RT(e.turnServer.servers)?t.iceServers=e.turnServer.servers:(t.iceServers&&t.iceServers.push(...iF.turnServerConfigToIceServers(e.turnServer.servers)),RC(\"USE_TURN_SERVER_OF_GATEWAY\")&&t.iceServers&&e.turnServer.serversFromGateway&&t.iceServers.push(...iF.turnServerConfigToIceServers(e.turnServer.serversFromGateway)),RC(\"FORCE_TURN_TCP\")?t.iceTransportPolicy=\"relay\":e.turnServer.servers.concat(e.turnServer.serversFromGateway||[]).forEach((e=>{e.forceturn&&(t.iceTransportPolicy=\"relay\")})))),t}static turnServerConfigToIceServers(e){const t=[];return e.forEach((e=>{e.security?e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:\"password\",urls:\"turns:\".concat(gy(e.turnServerURL),\":\").concat(e.tcpport,\"?transport=tcp\")}):(e.udpport&&!RC(\"FORCE_TURN_TCP\")&&t.push({username:e.username,credential:e.password,credentialType:\"password\",urls:\"turn:\".concat(e.turnServerURL,\":\").concat(e.udpport,\"?transport=udp\")}),e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:\"password\",urls:\"turn:\".concat(e.turnServerURL,\":\").concat(e.tcpport,\"?transport=tcp\")}))})),t}bindPCEvents(){this._p2pConnection.onICEConnectionStateChange=e=>{var t;return null===(t=this.onICEConnectionStateChange)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onConnectionStateChange=e=>{var t;return null===(t=this.onConnectionStateChange)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onDTLSTransportStateChange=e=>{var t;return null===(t=this.onDTLSTransportStateChange)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onDTLSTransportError=e=>{var t;return null===(t=this.onDTLSTransportError)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onICETransportStateChange=e=>{var t;return null===(t=this.onICETransportStateChange)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onFirstAudioReceived=e=>{var t;return null===(t=this.onFirstAudioReceived)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onFirstVideoReceived=e=>{var t;return null===(t=this.onFirstVideoReceived)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onFirstAudioDecoded=e=>{var t;return null===(t=this.onFirstAudioDecoded)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onFirstVideoDecoded=(e,t,i)=>{var n;return null===(n=this.onFirstVideoDecoded)||void 0===n?void 0:n.call(this,e,t,i)},this._p2pConnection.onFirstVideoDecodedTimeout=e=>{var t;return null===(t=this.onFirstVideoDecodedTimeout)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onSelectedLocalCandidateChanged=(e,t)=>{var i;return null===(i=this.onSelectedLocalCandidateChanged)||void 0===i?void 0:i.call(this,e,t)},this._p2pConnection.onSelectedRemoteCandidateChanged=(e,t)=>{var i;return null===(i=this.onSelectedRemoteCandidateChanged)||void 0===i?void 0:i.call(this,e,t)}}closeSignal(){this.dataChannel.close(),this.peerConnection.close()}unbindConnectionEvents(e){e.onConnectionStateChange=void 0,e.onICEConnectionStateChange=void 0,e.onICETransportStateChange=void 0,e.onDTLSTransportStateChange=void 0,e.onDTLSTransportError=void 0,e.onFirstAudioDecoded=void 0,e.onFirstAudioReceived=void 0,e.onFirstVideoDecoded=void 0,e.onFirstVideoReceived=void 0,e.onSelectedLocalCandidateChanged=void 0,e.onSelectedRemoteCandidateChanged=void 0,e.onFirstVideoDecodedTimeout=void 0}setConfiguration(e){this._p2pConnection.setConfiguration(e)}}function nF(e,t,i){const n=e[t];if(\"function\"!=typeof n)throw new Error(\"Cannot use mutex on object property.\");return i.value=async function(){const e=this.mutex,i=await e.lock(\"From DataChannelConnection.\".concat(t));try{for(var r=arguments.length,s=new Array(r),o=0;o{const n=await this.mutex.lock(\"Locking from P2PChannel.handleMuteLocalTrack\");try{if(!this.connection||this.state!==uv.Connected)return void i(new Kg(Hg.INVALID_OPERATION,\"Cannot call P2PChannel.handleMuteLocalTrack before connection established.\"));const r=this.filterTobeMutedTracks(e);if(0===r.length)return void t();const s=r.find((e=>\"videoLowTrack\"===e[0]));if(s){s[1].track._originMediaStreamTrack.stop()}await this.connection.muteLocal(r.map((e=>{let[,{id:t}]=e;return t})));const o=this.createMuteMessage(r);await yT(this,hv.RequestMuteLocal,o),t()}catch(e){i(e)}finally{n()}})),sh(this,\"handleUnmuteLocalTrack\",(async(e,t,i)=>{const n=await this.mutex.lock(\"Locking from P2PChannel.handleUnmuteLocalTrack\");try{if(!this.connection||this.state!==uv.Connected)return void i(new Kg(Hg.INVALID_OPERATION,\"Cannot call P2PChannel.handleUnmuteLocalTrack before connection established.\"));const r=this.filterTobeUnmutedTracks(e);if(0===r.length)return void t();const s=r.find((e=>\"videoLowTrack\"===e[0]));if(s){const t=s[1];if(t.track._originMediaStreamTrack.stop(),!RC(\"DISABLE_DUAL_STREAM_USE_ENCODING\")&&IA().supportDualStreamEncoding){const i=e._mediaStreamTrack.clone();t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i}else{const i=Gx(e,bT(this,hv.RequestLowStreamParameter));t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i}await new cg(((e,i)=>{this.handleReplaceTrack(t.track,e,i,!0)}))}await this.connection.unmuteLocal(r.map((e=>{let[,{id:t}]=e;return t})));const o=this.createUnmuteMessage(r);await yT(this,hv.RequestUnmuteLocal,o),t()}catch(e){i(e)}finally{n()}})),sh(this,\"handleUpdateVideoEncoder\",(async(e,t,i)=>{const n=await this.mutex.lock(\"Locking from P2PChannel.handleSetVideoEncoder\");try{const i=this.localTrackMap.get(lv.LocalVideoTrack);if(!this.connection||!i||i.track!==e||this.state!==uv.Connected)return void t();const{id:r,track:s}=i;await this.connection.updateSendParameters(r,s),await this.connection.updateEncoderConfig(r,s),this.emit(hv.UpdateVideoEncoder,s),t()}catch(e){i(e)}finally{n()}})),sh(this,\"handleSetOptimizationMode\",(async(e,t,i)=>{const n=await this.mutex.lock(\"Locking from P2PChannel.handleSetOptimizationMode\");try{const i=this.localTrackMap.get(lv.LocalVideoTrack);if(!this.connection||!i||i.track!==e||this.state!==uv.Connected)return;const{id:r,track:s}=i;await this.connection.updateSendParameters(r,s),t()}catch(e){i(e)}finally{n()}})),sh(this,\"handleReplaceMixingTrack\",(async(e,t,i,n)=>{if(!this.connection||this.state!==uv.Connected)return void t();const r=dV([e]);let s;jC.debug(\"[\".concat(this.store.clientId,\"] [p2pId: \").concat(this.store.p2pId,\"]: P2PConnection will replace audioTrack [\").concat(r.getTrackId(),\"]\")),\"boolean\"==typeof n&&n||(s=await this.mutex.lock(\"From P2PChannel.handleReplaceMixingTrack\"));try{await this.replaceTrack(e,r),t()}catch(e){i(e)}finally{var o;null===(o=s)||void 0===o||o()}})),sh(this,\"handleReplaceTrack\",(async(e,t,i,n)=>{let r;jC.debug(\"[\".concat(this.store.clientId,\"] P2PChannel handleReplaceTrack for [track-id-\").concat(e.getTrackId(),\"]\")),\"boolean\"==typeof n&&n||(r=await this.mutex.lock(\"From P2PChannel.handleReplaceTrack\"));try{var s;const i=Array.from(this.localTrackMap.entries()).find((t=>{let[,{track:i}]=t;return e===i}));if(!this.connection||!i||this.state!==uv.Connected)return void t();if(await(null===(s=this.connection)||void 0===s?void 0:s.replaceTrack(e,i[1].id)),this.isPlanB){const t=i[1];t.id=e._mediaStreamTrack.id,this.localTrackMap.set(i[0],t)}if(i[0]===lv.LocalVideoTrack&&!RC(\"DISABLE_DUAL_STREAM_USE_ENCODING\")&&IA().supportDualStreamEncoding){const t=this.localTrackMap.get(lv.LocalVideoLowTrack);if(t){const i=e._mediaStreamTrack.clone();t.track._originMediaStreamTrack.stop(),t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i,await new cg(((e,i)=>{this.handleReplaceTrack(t.track,e,i,!0)}))}}t()}catch(e){i(e)}finally{var o;null===(o=r)||void 0===o||o()}})),sh(this,\"handleGetRTCStats\",(e=>{e(this.statsCollector.getRTCStats())})),sh(this,\"handleGetLocalVideoStats\",(e=>{e(this.statsCollector.getLocalVideoTrackStats())})),sh(this,\"handleGetLocalAudioStats\",(e=>{e(this.statsCollector.getLocalAudioTrackStats())})),sh(this,\"handleGetRemoteVideoStats\",(e=>this.statsCollector.getRemoteVideoTrackStats(e.uid)[e.uid])),sh(this,\"handleGetRemoteAudioStats\",(e=>this.statsCollector.getRemoteAudioTrackStats(e.uid)[e.uid])),this.store=e,this.statsCollector=t,this.statsCollector.addP2PChannel(this),this.statsUploader=new rV(this.store),this.bindStatsUploaderEvents(),this.isPlanB=!IA().supportUnifiedPlan||RC(\"CHROME_FORCE_PLAN_B\")&&jg(),this.shouldForwardP2PCreation=RC(\"FORWARD_P2P_CREATION\")&&IA().supportPCSetConfiguration&&function(){const e=Rg();return e===_g.ANDROID||e===_g.IOS||e===_g.HARMONY_OS}(),this.shouldForwardP2PCreation&&(this.connection=this.store.useDataChannel?new iF({},this.store):this.isPlanB?new LV({},this.store):new jV({},this.store),this.bindConnectionEvents(this.connection))}async startP2PConnection(e,t){var i;this.state=uv.New;const n=this.shouldForwardP2PCreation&&\"closed\"===(null===(i=this.connection)||void 0===i?void 0:i.peerConnectionState);if(this.shouldForwardP2PCreation&&!n||(n&&this.connection&&(jC.warning(\"[\".concat(this.store.clientId,\"] P2PChannel.startP2PConnection ForwardP2P closed.\")),this.connection.close(),this.unbindConnectionEvents(this.connection)),this.connection=this.store.useDataChannel?new iF(e,this.store):this.isPlanB?new LV(e,this.store):new jV(e,this.store),this.bindConnectionEvents(this.connection)),!this.connection)throw new Kg(Hg.UNEXPECTED_ERROR,\"Cannot P2PChannel.startConnection before P2PConnection initialization .\");return this._pcStatsUploadType=RC(\"NEW_ICE_RESTART\")?dv.FIRST_CONNECTION:dv.OLD_FIRST_CONNECTION,this._isFirstConnected=!0,this._isInRestartIce=!1,this._isStartRestartIce=!1,this.connection.setConfiguration(e),this.connection.establishPromise}async connect(e,t,i,n,r,s){if(!this.connection)throw new Kg(Hg.UNEXPECTED_ERROR,\"Cannot P2PChannel.connect before P2PChannel.startP2PConnection .\");this.connection instanceof iF?this.connection.updateRemoteConnect(n):(this.store.peerConnectionStart(),await this.connection.connect(e,t,i,n,r,s),this.statsUploader.startUploadTransportStats(),this.statsUploader.startUploadExtensionUsageStats(),this.state=uv.Connected)}updateRemoteRTPCapabilities(e){const t=Array.from(this.localTrackMap.entries()).filter((e=>{var t;let[i]=e;return bn(t=[lv.LocalVideoLowTrack,lv.LocalVideoTrack]).call(t,i)})),i=t.map((e=>{let[,{id:t}]=e;return t})),n=t.map((e=>{let[t]=e;return t}));if(this.connection instanceof jV){if(eI.updateRemoteRTPCapabilities(this.store.sessionId,{trackTypes:JSON.stringify(n),localCodecs:JSON.stringify(this.connection.localCodecs),remoteCodecs:JSON.stringify(e)}),!bn(e).call(e,this.store.codec)){const t=[\"vp8\",\"h264\"].find((t=>bn(e).call(e,t)));t&&(this.store.codec=t,jC.debug(\"[\".concat(this.store.clientId,\"] [\").concat(this.store.p2pId,\" updateRemoteRTPCapabilities] default codec is not available, hence the fallback to \").concat(t,\".\")))}this.connection.updateRemoteRTPCapabilities(i,e)}}async preConnect(e,t,i,n,r,s){if(!this.connection)throw new Kg(Hg.UNEXPECTED_ERROR,\"Cannot P2PChannel.connect before P2PChannel.startP2PConnection .\");this.store.peerConnectionStart();const o=await this.connection.connect(e,t,i,n,r,s);return this.statsUploader.startUploadTransportStats(),this.statsUploader.startUploadExtensionUsageStats(),this.state=uv.Connected,o}getEstablishParams(){if(this.connection instanceof iF)return this.connection.getP2PConnectionParams();throw new Error(\"Only DataChannelConnection needs to obtain establishParams\")}async publishDataChannel(e){if(!this.connection||this.state!==uv.Connected){if(this.state===uv.Disconnected)throw new Kg(Hg.UNEXPECTED_ERROR,\"PeerConnection already disconnected.\");return void e.forEach((e=>{var t;bn(t=this.pendingLocalDataChannels).call(t,e)||this.pendingLocalDataChannels.push(e)}))}const t=this.filterTobePublishedDataChannels(e);0!==t.length&&(t.forEach((e=>{const t=Date.now();this.store.publish(e.id.toString(),\"datachannel\",t)})),await this.connection.createDataChannels(this.store.uid,t),t.forEach((e=>{this.localDataChannels.push(e);const t=Date.now();this.store.publish(e.id+\"\",\"datachannel\",void 0,t)})))}publish(e,t,i){var n=this;return PU((function*(){const r=yield IU(n.mutex.lock(\"From P2PChannel.publish\"));try{if(!n.connection||n.state!==uv.Connected){if(n.state===uv.Disconnected)throw new Kg(Hg.UNEXPECTED_ERROR,\"PeerConnection already disconnected.\");n.throwIfTrackTypeNotMatch(e);const t=e.filter((e=>-1===n.pendingLocalTracks.indexOf(e)));return void(n.pendingLocalTracks=n.pendingLocalTracks.concat(t))}n.store.pubId=n.store.pubId+1,RU.markPublishStart(n.store.clientId,n.store.pubId);const s=n.filterTobePublishedTracks(e,t,i);if(0===s.length)return void(yield IU(n.tryToUnmuteAudio(e)));yield*bV(oF(n.doPublish(n.connection,s)))}finally{r()}}))()}doPublish(e,t){var i=this;return PU((function*(){t.forEach((e=>{let{track:t,type:n}=e;const r=Date.now();i.store.publish(t.getTrackId(),n===lv.LocalAudioTrack?\"audio\":\"video\",r)})),i.bindLocalTrackEvents(t);const n=t.map((e=>{let{track:t}=e;return t})),r=yield IU(e.send(t.map((e=>{let{track:t}=e;return t})),i.store.codec,i.store.audioCodec)),s=(yield IU(r.next())).value,o=i.createGatewayPublishMessage(t,s);let a;try{a=yield o}catch(e){throw r.throw(e),(null==e?void 0:e.code)===Hg.WS_ABORT&&t.forEach((e=>{let{track:t}=e;-1===i.pendingLocalTracks.indexOf(t)&&i.pendingLocalTracks.push(t)})),i.unbindLocalTrackEvents(t),e}const c=i.mapPubResToRemoteConfig(o,a),d=(yield IU(r.next(c))).value,l=RC(\"ENABLE_VIDEO_SEI\");n.forEach((async e=>{const t=e.getRTCRtpTransceiver();t&&l&&(e.trackMediaType===av.VIDEO?await async function(e,t){if(!IA().supportWebRTCEncodedTransform)return void jC.warning(\"browser not support video encoded transform\");if(mU.has(e))return;if(!e.track)return;const i={track:e.track};if(Ag()){if(!e.createEncodedStreams)return void jC.warning(\"browser not support createEncodedStreams() API\");let r=null;try{r=e.createEncodedStreams()}catch(e){return void jC.error(\"create video-encoded-streams error\",e&&e.message)}let s=[];t.on(\"sei-to-send\",(e=>{s.push(e)}));const o=new TransformStream({transform(t,r){i.controller||(i.controller=r),e.track&&e.track.id!==i.track.id&&(jC.debug(\"video track changed: \".concat(i.track.id,\" => \").concat(e.track.id)),i.track.removeEventListener(\"ended\",n),i.track=e.track,i.track.addEventListener(\"ended\",n));const o=s.shift();o&&(t.data=EU(t.data,o)),r.enqueue(t)}});r.readable.pipeThrough(o).pipeTo(r.writable)}else{if(!bg())return;{if(\"undefined\"==typeof RTCRtpScriptTransform)return void jC.warning(\"browser not support RTCRtpScriptTransform\");const r=lU(),s=new MessageChannel;await new cg((e=>r.onmessage=t=>{\"registered\"===t.data&&e(void 0)}));const o=new RTCRtpScriptTransform(r,{name:\"tx\",port:s.port2},[s.port2]);e.transform=o,await new cg((e=>r.onmessage=t=>{\"started\"===t.data&&e(void 0)})),t.on(\"sei-to-send\",(e=>{s.port1.postMessage({sei:e})})),s.port1.onmessage=t=>{var r;t.data.transformed&&e.track&&(null===(r=e.track)||void 0===r?void 0:r.id)!==i.track.id&&(jC.debug(\"video track changed: \".concat(i.track.id,\" => \").concat(e.track.id)),i.track.removeEventListener(\"ended\",n),i.track=e.track,i.track.addEventListener(\"ended\",n))},i.worker=r}}function n(){if(e.track){if(this.id!==e.track.id)return;e.track.removeEventListener(\"ended\",n)}const t=mU.get(e);if(t){mU.delete(e);try{var i,r;null===(i=t.controller)||void 0===i||i.terminate(),null===(r=t.worker)||void 0===r||r.terminate()}catch(e){jC.warning(e&&e.message)}}}mU.set(e,i),e.track.addEventListener(\"ended\",n)}(t.sender,e):e.trackMediaType===av.AUDIO&&await async function(e){if(!IA().supportWebRTCEncodedTransform)return void jC.warning(\"browser not support audio encoded transform\");if(uU.has(e))return;if(!e.track)return;const t={track:e.track};if(Ag()){if(!e.createEncodedStreams)return void jC.warning(\"browser not support createEncodedStreams() API\");let n=null;try{n=e.createEncodedStreams()}catch(e){return void jC.error(\"create audio-encoded-streams error\",e&&e.message)}const r=new TransformStream({transform(n,r){t.controller||(t.controller=r),e.track&&e.track.id!==t.track.id&&(jC.debug(\"audio track changed: \".concat(t.track.id,\" => \").concat(e.track.id)),t.track.removeEventListener(\"ended\",i),t.track=e.track,t.track.addEventListener(\"ended\",i)),r.enqueue(n)}});n.readable.pipeThrough(r).pipeTo(n.writable)}else if(bg()){if(\"undefined\"==typeof RTCRtpScriptTransform)return void jC.warning(\"browser not support RTCRtpScriptTransform\");const n=lU(),r=new MessageChannel;await new cg((e=>n.onmessage=t=>{\"registered\"===t.data&&e(void 0)}));const s=new RTCRtpScriptTransform(n,{name:\"tx\",port:r.port2},[r.port2]);e.transform=s,await new cg((e=>n.onmessage=t=>{\"started\"===t.data&&e(void 0)})),r.port1.onmessage=n=>{var r;n.data.transformed&&e.track&&(null===(r=e.track)||void 0===r?void 0:r.id)!==t.track.id&&(jC.debug(\"audio track changed: \".concat(t.track.id,\" => \").concat(e.track.id)),t.track.removeEventListener(\"ended\",i),t.track=e.track,t.track.addEventListener(\"ended\",i))},t.worker=n}function i(){if(e.track){if(this.id!==e.track.id)return;e.track.removeEventListener(\"ended\",i)}const t=uU.get(e);if(t){uU.delete(e);try{var n,r;null===(n=t.controller)||void 0===n||n.terminate(),null===(r=t.worker)||void 0===r||r.terminate()}catch(e){jC.warning(e&&e.message)}}}uU.set(e,t),e.track.addEventListener(\"ended\",i)}(t.sender))})),t.forEach((e=>{let{type:t}=e;i.statsCollector.addLocalStats(t)})),i.assignLocalTracks(t,d),i.statsUploader.startUploadOutboundStats(),t.forEach((e=>{let{track:t,type:n}=e;const r=Date.now();i.store.publish(t.getTrackId(),n===lv.LocalAudioTrack?\"audio\":\"video\",void 0,r)}))}))()}async updateVideoStreamParameter(e,t){const i=this.localTrackMap.get(t);if(!i)return;if(!(i.track instanceof Rw))return jC.warn(\"[updateVideoStreamParameter]: track is not an instance of LocalVideoTrack\");if(!(this.connection instanceof jV||this.connection instanceof LV))return jC.warn(\"[updateVideoStreamParameter]: connection is not P2PConnection or P2PConnectionPlanB\");const{track:n}=i,r=function(e,t){const i={};return e.height&&e.width&&(i.scaleResolutionDownBy=yy(e,t)),i.maxFramerate=e.framerate?Sy(e.framerate):void 0,i.maxBitrate=e.bitrate?1e3*e.bitrate:void 0,i}(e,n);if(n._encoderConfig||(n._encoderConfig={}),t!==lv.LocalVideoLowTrack||!RC(\"DISABLE_DUAL_STREAM_USE_ENCODING\")&&IA().supportDualStreamEncoding)null!=r.scaleResolutionDownBy&&(n._encoderConfig.scaleResolutionDownBy=r.scaleResolutionDownBy);else{const t=n._originMediaStreamTrack;if(!t.canvas)return jC.warn(\"[\".concat(n.getTrackId(),\"] no canvas on track\"));!function(e,t){const i=e.canvas;t.width&&(i.width=Sy(t.width)),t.height&&(i.height=Sy(t.height)),t.framerate&&(i.stopCapture&&i.stopCapture(),i.stopCapture=Tb((()=>{!i.startCapture&&i.stopCapture&&i.stopCapture(),i.startCapture&&i.startCapture()}),Sy(t.framerate)))}(t,e)}null!=r.maxBitrate&&(n._encoderConfig.bitrateMax=r.maxBitrate/1e3),null!=r.maxFramerate&&(n._encoderConfig.frameRate&&\"object\"==typeof n._encoderConfig.frameRate?n._encoderConfig.frameRate.max=r.maxFramerate:n._encoderConfig.frameRate={max:r.maxFramerate}),jC.debug(\"[\".concat(n.getTrackId(),\"] LowStreamEncoderConfig: , \").concat(JSON.stringify(n._encoderConfig))),await this.connection.updateRtpSenderEncodings(n)}publishLowStream(e){var t=this;return PU((function*(){if(!t.connection||t.state!==uv.Connected)return;const i=yield IU(t.mutex.lock(\"Locking from P2PChannel.publishLowStream\"));try{const r=t.localTrackMap.get(lv.LocalVideoTrack);if(!r)throw new Kg(Hg.UNEXPECTED_ERROR,\"Could not find high stream\");if(t.localTrackMap.has(lv.LocalVideoLowTrack))throw new Kg(Hg.UNEXPECTED_ERROR,\"[\".concat(t.store.clientId,\"] Can't publish low stream when stream already publish\"));const s=[{track:t.getLowVideoTrack(r.track,e),type:lv.LocalVideoLowTrack}];if(yield*bV(oF(t.doPublish(t.connection,s))),r.track.muted||!r.track.enabled){var n;const e=null===(n=t.localTrackMap.get(lv.LocalVideoLowTrack))||void 0===n?void 0:n.id;void 0!==e&&(yield IU(t.connection.muteLocal([e])))}}finally{i()}}))()}async republish(){this.pendingLocalTracks.length>0&&(jC.debug(\"[\".concat(this.store.clientId,\"] Emit P2PChannelEvents.RequestRePublish to republish tracks.\")),await vT(this,hv.RequestRePublish,this.pendingLocalTracks),this.emit(hv.MediaReconnectEnd,this.store.uid),this.pendingLocalTracks=[]),this.pendingLocalDataChannels.length>0&&(jC.debug(\"Emit P2PChannelEvents.RequestRePublishDataChannel to republish datachannels.\"),await vT(this,hv.RequestRePublishDataChannel,this.pendingLocalDataChannels),this.pendingLocalDataChannels=[])}async reSubscribe(e){for(let e=this.pendingRemoteTracks.length-1;e>=0;e--){const{user:t,kind:i}=this.pendingRemoteTracks[e];(i!==av.AUDIO||t._audio_added_&&t._audioSSRC)&&(i!==av.VIDEO||t._video_added_&&t._videoSSRC)||this.pendingRemoteTracks.splice(e,1)}if(e)await vT(this,hv.RequestReSubscribe,this.pendingRemoteTracks);else for(const{user:e,kind:t}of this.pendingRemoteTracks)await this.subscribe(e,t,t===av.VIDEO?e._videoSSRC:e._audioSSRC);this.pendingRemoteTracks.forEach((e=>{let{user:t}=e;this.emit(hv.MediaReconnectEnd,t.uid)})),this.pendingRemoteTracks=[]}async unpublish(e){if(!this.connection||this.state!==uv.Connected)return void e.forEach((e=>{const t=this.pendingLocalTracks.indexOf(e);-1!==t&&this.pendingLocalTracks.splice(t,1)}));const t=this.filterTobeUnpublishedTracks(e);if(0===t.length)return;const i=t.find((e=>\"videoLowTrack\"===e[0]));if(i){i[1].track.close()}return this.doUnpublish(this.connection,t)}async unpublishDataChannel(e){if(!this.connection||this.state!==uv.Connected)return void e.forEach((e=>{const t=this.pendingLocalDataChannels.indexOf(e);-1!==t&&this.pendingLocalDataChannels.splice(t,1)}));const t=this.filterTobeUnpublishedDataChannels(e);return 0!==t.length?(t.forEach((e=>{const t=this.localDataChannels.indexOf(e);-1!==t&&this.localDataChannels.splice(t,1)})),0===this.localDataChannels.length&&await this.connection.stopDataChannels(this.store.uid),t.map((e=>e.id))):void 0}async unpublishLowStream(){if(!this.connection||this.state!==uv.Connected)return;const e=this.localTrackMap.get(lv.LocalVideoLowTrack);if(!e)return;e.track.close();const t=[[lv.LocalVideoLowTrack,e]];return this.doUnpublish(this.connection,t)}async doUnpublish(e,t){const i=this.createGatewayUnpublishMessage(t);return await e.stopSending(t.map((e=>{let[,{id:t}]=e;return t}))),this.withdrawLocalTracks(t),this.unbindLocalTrackEvents(t.map((e=>{let[t,{track:i}]=e;return{type:t,track:i}}))),t.forEach((e=>{let[t]=e;this.statsCollector.removeLocalStats(t)})),0===this.localTrackMap.size&&this.statsUploader.stopUploadOutboundStats(),i}async subscribeDataChannel(e,t){if(!this.connection||this.state!==uv.Connected)throw new Kg(Hg.INVALID_OPERATION,\"Cannot subscribe remote user when peerConnection disconnected.\");const i=t.filter((t=>{var i;return!(null!==(i=this.remoteDataChannelMap.get(e))&&void 0!==i&&i.get(t.id))}));if(0!==i.length)return await this.connection.createDataChannels(e.uid,i),i.forEach((t=>{var i;this.remoteDataChannelMap.has(e)?null===(i=this.remoteDataChannelMap.get(e))||void 0===i||i.set(t.id,t):this.remoteDataChannelMap.set(e,new Map([[t.id,t]]));const n=this.pendingRemoteDataChannels.findIndex((i=>{let{user:n,id:r}=i;return n.uid===e.uid&&r===t.id}));-1!==n&&this.pendingRemoteDataChannels.splice(n,1)})),i.map((e=>e.id))}async subscribe(e,t,i,n,r){var s;if(!this.connection||this.state!==uv.Connected)throw new Kg(Hg.INVALID_OPERATION,\"Cannot subscribe remote user when peerConnection disconnected.\");if(null!==(s=this.remoteUserMap.get(e))&&void 0!==s&&s.has(t))return;let o,a,c;if(r){const i=r.find((e=>{let{stream_type:i}=e;return i===t}));if(!i)throw new Kg(Hg.UNEXPECTED_ERROR,\"Cannot subscribe to remote \".concat(t,\" for user: \").concat(e.uid,\" because subscribe answer from gateway does not contain stream_type: \").concat(t,\".\"));const n=await this.connection.receive(t,i.ssrcs,String(e._uintid),i.attributes);this.connection instanceof jV&&(c=n.transceiver),o=n.track,a=n.id}else{const r=await this.connection.receive(t,[{ssrcId:i,rtx:n}],String(e._uintid),void 0);this.connection instanceof jV&&(c=r.transceiver),o=r.track,a=r.id}t===av.AUDIO?(e._audioTrack?e._audioTrack._updateOriginMediaStreamTrack(o):(e._audioTrack=new Nw(o,e.uid,e._uintid,this.store),jC.info(\"[\".concat(this.store.clientId,\"] [\").concat(this.store.p2pId,\"] create remote audio track: \").concat(e._audioTrack.getTrackId()))),c&&e._audioTrack._updateRtpTransceiver(c),this.bindRemoteTrackEvents(e,e._audioTrack)):(e._videoTrack?e._videoTrack._updateOriginMediaStreamTrack(o):(e._videoTrack=new Ow(o,e.uid,e._uintid,this.store),jC.info(\"[\".concat(this.store.clientId,\"] [\").concat(this.store.p2pId,\"] create remote video track: \").concat(e._videoTrack.getTrackId()))),c&&e._videoTrack._updateRtpTransceiver(c),this.bindRemoteTrackEvents(e,e._videoTrack)),RC(\"ENABLE_VIDEO_SEI\")&&c&&(t==av.VIDEO?await gU(c.receiver,{onSei:t=>{var i;null===(i=e._videoTrack)||void 0===i||i._onSei(t)}}):t==av.AUDIO&&await pU(c.receiver));const d=this.remoteUserMap.get(e);d?d.set(t,a):this.remoteUserMap.set(e,new Map([[t,a]])),this.statsCollector.addRemoteStats(e.uid),this.statsUploader.startUploadInboundStats();const l=this.pendingRemoteTracks.findIndex((i=>{let{user:n,kind:r}=i;return n.uid===e.uid&&t===r}));-1!==l&&(this.pendingRemoteTracks.splice(l,1),this.emit(hv.MediaReconnectEnd,e.uid))}async massSubscribe(e){return this.massSubscribeNoLock(e)}async massSubscribeNoLock(e){if(!this.connection||this.state!==uv.Connected)throw new Kg(Hg.INVALID_OPERATION,\"Cannot subscribeAll remote users when peerConnection disconnected.\");e=e.filter((e=>{var t;let{user:i,mediaType:n}=e;return!(null!==(t=this.remoteUserMap.get(i))&&void 0!==t&&t.has(n))}));const t=await this.connection.batchReceive(e.map((e=>{let{user:t,mediaType:i,ssrcId:n,rtxSsrcId:r}=e;return{kind:i,ssrcMsg:[{ssrcId:n,rtx:r}],mslabel:String(t._uintid)}})));e.forEach(((e,i)=>{let{user:n,mediaType:r}=e;const{track:s,id:o,transceiver:a}=t[i];r===av.AUDIO?(n._audioTrack?n._audioTrack._updateOriginMediaStreamTrack(s):(n._audioTrack=new Nw(s,n.uid,n._uintid,this.store),jC.info(\"[\".concat(this.store.clientId,\"] [\").concat(this.store.p2pId,\"] create remote audio track: \").concat(n._audioTrack.getTrackId()))),a&&n._audioTrack._updateRtpTransceiver(a),this.bindRemoteTrackEvents(n,n._audioTrack)):(n._videoTrack?n._videoTrack._updateOriginMediaStreamTrack(s):(n._videoTrack=new Ow(s,n.uid,n._uintid,this.store),jC.info(\"[\".concat(this.store.clientId,\"] [\").concat(this.store.p2pId,\"] create remote video track: \").concat(n._videoTrack.getTrackId()))),a&&n._videoTrack._updateRtpTransceiver(a),this.bindRemoteTrackEvents(n,n._videoTrack));const c=this.remoteUserMap.get(n);c?c.set(r,o):this.remoteUserMap.set(n,new Map([[r,o]])),this.statsCollector.addRemoteStats(n.uid),this.statsUploader.startUploadInboundStats();const d=this.pendingRemoteTracks.findIndex((e=>{let{user:t,kind:i}=e;return t.uid===n.uid&&r===i}));-1!==d&&(this.pendingRemoteTracks.splice(d,1),this.emit(hv.MediaReconnectEnd,n.uid))}))}async unsubscribe(e,t,i){const n=this.pendingRemoteTracks.filter((i=>{let{user:n,kind:r}=i;return void 0!==t?n.uid===e.uid&&t===r:n.uid===e.uid}));if(n.forEach((e=>{const t=this.pendingRemoteTracks.indexOf(e);this.pendingRemoteTracks.splice(t,1)})),this.connection&&this.state===uv.Connected||i||n.forEach((t=>{let{kind:i}=t;var n;if(i===av.AUDIO)null===(n=e._audioTrack)||void 0===n||n._destroy(),e._audioTrack=void 0;else if(i===av.VIDEO){var r;null===(r=e._videoTrack)||void 0===r||r._destroy(),e._videoTrack=void 0}})),!this.connection||this.state!==uv.Connected)return;const r=this.filterTobeUnSubscribedTracks(e,t);if(0===r.length)return;await this.connection.stopReceiving(r.map((e=>{let[,{id:t}]=e;return t})));const s=this.createUnsubscribeMessage(r);return this.withdrawRemoteTracks(r),0===this.remoteUserMap.size&&this.statsUploader.stopUploadInboundStats(),r.forEach((e=>{let[t,{kind:n}]=e;var r,s;n===av.VIDEO&&t._videoSSRC&&(null===(r=this.connection)||void 0===r||r.setStatsRemoteVideoIsReady(t._videoSSRC,!1));if(n===av.VIDEO)this.unbindRemoteTrackEvents(t._videoTrack),i||(null===(s=t._videoTrack)||void 0===s||s._destroy(),t._videoTrack=void 0);else if(n===av.AUDIO){var o;if(this.unbindRemoteTrackEvents(t._audioTrack),!i)null===(o=t._audioTrack)||void 0===o||o._destroy(),t._audioTrack=void 0}})),s}async unsubscribeDataChannel(e,t){if(t.forEach((e=>{const t=this.pendingRemoteDataChannels.findIndex((t=>t.id===e.id));-1!==t&&this.pendingRemoteDataChannels.splice(t,1)})),!this.connection)return;const i=this.filterTobeUnSubscribedDataChannels(e,t);if(0===i.length)return;t.forEach((e=>{e._close()}));const n=this.remoteDataChannelMap.get(e);return i.forEach((e=>{n&&n.delete(e.id)})),n&&0===n.size&&(this.remoteDataChannelMap.delete(e),await this.connection.stopDataChannels(e.uid)),i.map((e=>e.id))}async massUnsubscribe(e){return this.massUnsubscribeNoLock(e)}async massUnsubscribeNoLock(e){let t=[];for(const{user:i,mediaType:n}of e){const e=this.pendingRemoteTracks.filter((e=>{let{user:t,kind:r}=e;return void 0!==n?t.uid===i.uid&&n===r:t.uid===i.uid}));e.forEach((e=>{const t=this.pendingRemoteTracks.indexOf(e);this.pendingRemoteTracks.splice(t,1)})),t=t.concat(e)}if(!this.connection||this.state!==uv.Connected)return void t.forEach((e=>{let{user:t,kind:i}=e;var n;if(i===av.AUDIO)null===(n=t._audioTrack)||void 0===n||n._destroy(),t._audioTrack=void 0;else if(i===av.VIDEO){var r;null===(r=t._videoTrack)||void 0===r||r._destroy(),t._videoTrack=void 0}}));const i=BT(e).call(e,((e,t)=>{let{user:i,mediaType:n}=t;const r=this.filterTobeUnSubscribedTracks(i,n);return e.concat(r)}),[]);if(0===i.length)return;await this.connection.stopReceiving(i.map((e=>{let[,{id:t}]=e;return t})));const n=this.createUnsubscribeAllMessage(i);return this.withdrawRemoteTracks(i),0===this.remoteUserMap.size&&this.statsUploader.stopUploadInboundStats(),i.forEach((e=>{let[t,{kind:i}]=e;var n,r;i===av.VIDEO&&t._videoSSRC&&(null===(n=this.connection)||void 0===n||n.setStatsRemoteVideoIsReady(t._videoSSRC,!1));if(i===av.VIDEO)this.unbindRemoteTrackEvents(t._videoTrack),null===(r=t._videoTrack)||void 0===r||r._destroy(),t._videoTrack=void 0;else if(i===av.AUDIO){var s;this.unbindRemoteTrackEvents(t._audioTrack),null===(s=t._audioTrack)||void 0===s||s._destroy(),t._audioTrack=void 0}})),n}async muteRemote(e,t){if(!this.connection)return;const i=this.remoteUserMap.get(e);if(!i)return void jC.warning(\"[\".concat(this.store.clientId,\"] P2PChannel.muteRemote has no remote user \").concat(e.uid,\".\"));if(!i.get(t))return void jC.warning(\"[\".concat(this.store.clientId,\"] P2PChannel.muteRemote has no remote user \").concat(e.uid,\" media type \").concat(t,\".\"));const n=t===av.VIDEO?e._videoSSRC:e._audioSSRC;void 0!==n&&this.connection.setStatsRemoteVideoIsReady(n,!1)}async unmuteRemote(e,t){return this.unmuteRemoteNoLock(e,t)}async unmuteRemoteNoLock(e,t){if(!this.connection)return;const i=this.remoteUserMap.get(e);if(!i)return void jC.warning(\"[\".concat(this.store.clientId,\"] P2PChannel.unmuteRemote has no remote user \").concat(e.uid,\".\"));i.get(t)||jC.warning(\"[\".concat(this.store.clientId,\"] P2PChannel.unmuteRemote has no remote user \").concat(e.uid,\" media type \").concat(t,\".\"))}getAllTracks(e){const t=this.localTrackMap.get(lv.LocalAudioTrack);if((null==t?void 0:t.track)instanceof nw){const i=t.track;return Array.from(this.localTrackMap.entries()).filter((e=>{let[t]=e;return t!==lv.LocalAudioTrack})).filter((t=>{let[i]=t;return!(e&&i===lv.LocalVideoLowTrack)})).map((e=>{let[,{track:t}]=e;return t})).concat(i.trackList)}return Array.from(this.localTrackMap.entries()).filter((t=>{let[i]=t;return!(e&&i===lv.LocalVideoLowTrack)})).map((e=>{let[,{track:t}]=e;return t}))}getAllDataChannels(){return this.localDataChannels}reportPublishEvent(e,t,i,n,r){if(e){const i=this.localTrackMap.get(lv.LocalAudioTrack),s=n?this.localTrackMap.get(lv.LocalVideoLowTrack):this.localTrackMap.get(lv.LocalVideoTrack);eI.publish(this.store.sessionId,{eventElapse:RU.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:e,ec:t,audioName:null==i?void 0:i.track.getTrackLabel(),videoName:null==s?void 0:s.track.getTrackLabel(),screenshare:-1!==(null==s?void 0:s.track._hints.indexOf(jA.SCREEN_TRACK)),audio:!!i,video:!!s,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r})}else{var s;i||(i=[]);const o=i.find((e=>e instanceof ew)),a=n?null===(s=this.localTrackMap.get(lv.LocalVideoTrack))||void 0===s?void 0:s.track:i.find((e=>e instanceof Rw));eI.publish(this.store.sessionId,{eventElapse:RU.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:e,ec:t,audioName:null==o?void 0:o.getTrackLabel(),videoName:null==a?void 0:a.getTrackLabel(),screenshare:-1!==(null==a?void 0:a._hints.indexOf(jA.SCREEN_TRACK)),audio:!!o,video:!!a,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r})}}reportSubscribeEvent(e,t,i,n){const r=n===av.VIDEO?i._videoSSRC:i._audioSSRC;r&&eI.subscribe(this.store.sessionId,{succ:e,ec:t,video:n===av.VIDEO,audio:n===av.AUDIO,peerid:i.uid,subscribeRequestid:n===av.VIDEO?i._videoSSRC:i._audioSSRC,p2pid:this.store.p2pId,eventElapse:RU.measureFromSubscribeStart(this.store.clientId,r)})}reset(){jC.debug(\"[\".concat(this.store.clientId,\"] P2PChannel.reset\")),this.mutex=new pS(\"P2PChannel-mutex\"),this.connection&&(this.connection.close(),this.unbindConnectionEvents(this.connection),this.connection=void 0),this.shouldForwardP2PCreation&&(this.connection=this.store.useDataChannel?new iF({},this.store):this.isPlanB?new LV({},this.store):new jV({},this.store),this.bindConnectionEvents(this.connection)),this.statsUploader.stopUploadOutboundStats(),this.statsUploader.stopUploadInboundStats(),this.statsUploader.stopUploadTransportStats(),this.statsUploader.stopUploadExtensionUsageStats(),this.unbindLocalTrackEvents(),this.unbindAllRemoteTrackEvents(),this.unbindRtpTransceiver();const e=this.localTrackMap.get(lv.LocalAudioTrack);if((null==e?void 0:e.track)instanceof nw){if(e.track.trackList.length>0){const t=e.track;e.track.trackList.forEach((e=>{t.removeAudioTrack(e)}))}e.track.close()}this.localTrackMap.clear(),this.remoteUserMap.clear(),this.statsCollector.removeRemoteStats(),this.statsCollector.removeLocalStats(),this.iceFailedCount=0,this.dtlsFailedCount=0,this.pendingLocalTracks=[],this.pendingRemoteTracks=[],this.localDataChannels=[],this.remoteDataChannelMap.clear(),this.pendingLocalDataChannels=[],this.pendingRemoteDataChannels=[],this.state=uv.Disconnected}getStats(){var e;return null===(e=this.connection)||void 0===e?void 0:e.getStats()}getRemoteVideoIsReady(e){var t;return(null===(t=this.connection)||void 0===t?void 0:t.getRemoteVideoIsReady(e))||!1}getLocalAudioVolume(){const e=this.localTrackMap.get(lv.LocalAudioTrack);if(e)return e.track.getVolumeLevel()}getLocalVideoSize(){const e=this.localTrackMap.get(lv.LocalVideoTrack);if(e)return{width:e.track._videoWidth||0,height:e.track._videoHeight||0}}getEncoderConfig(e){const t=this.localTrackMap.get(e);return t&&t.track instanceof Rw||t&&t.track instanceof ew?t.track._encoderConfig:void 0}getLocalMedia(e){return this.localTrackMap.get(e)}hasLocalMedia(){return this.localTrackMap.size>0}hasRemoteMedia(e,t){if(!e)return this.remoteUserMap.size>0;const i=this.remoteUserMap.get(e);return!!i&&(!t||i.has(t))}async hasRemoteMediaWithLock(e,t){if(!e)return this.remoteUserMap.size>0;const i=this.remoteUserMap.get(e);return!!i&&(!t||i.has(t))}getRemoteMedia(e){var t;const i=Array.from(ph(t=this.remoteUserMap).call(t)).find((t=>t.uid===e));return i?{audioTrack:i.audioTrack,audioSSRC:i._audioSSRC,videoTrack:i.videoTrack,videoSSRC:i._videoSSRC}:{}}getAudioLevels(){let e=Array.from(this.remoteUserMap.entries()).map((e=>{let[t]=e;return{uid:t.uid,level:t.audioTrack?100*t.audioTrack._source.getAccurateVolumeLevel():0}}));const t=this.localTrackMap.get(lv.LocalAudioTrack);return t&&e.push({level:100*t.track._source.getAccurateVolumeLevel(),uid:this.store.uid}),e=ep(e).call(e,((e,t)=>e.level-t.level)),e}async disconnectForReconnect(){this.connection&&(jC.debug(\"[\".concat(this.store.clientId,\"] P2PChannel.disconnectForReconnect closing P2PConnection\")),this.state=uv.Reconnecting,RC(\"KEEP_LAST_FRAME\")&&0!==this.remoteUserMap.size&&Array.from(this.remoteUserMap.entries()).forEach((e=>{let[t]=e;var i;t._videoTrack&&t._videoTrack._player&&(null===(i=t._videoTrack._player.getVideoElement())||void 0===i||i.pause(),t._videoTrack._player.isKeepLastFrame=!0,t._videoTrack._originMediaStreamTrack.stop())})),this.connection.close(),this.unbindConnectionEvents(this.connection),this.connection=void 0,this.shouldForwardP2PCreation&&(this.connection=this.store.useDataChannel?new iF({},this.store):this.isPlanB?new LV({},this.store):new jV({},this.store),this.bindConnectionEvents(this.connection)),0!==this.localTrackMap.size&&(Array.from(this.localTrackMap.entries()).forEach((e=>{var t;let[i,{track:n}]=e;switch(i){case lv.LocalVideoTrack:bn(t=n._hints).call(t,jA.LOW_STREAM)?n.close():this.pendingLocalTracks.push(n);break;case lv.LocalAudioTrack:n instanceof nw?this.pendingLocalTracks=this.pendingLocalTracks.concat(n.trackList):this.pendingLocalTracks.push(n);case lv.LocalVideoLowTrack:}})),this.emit(hv.MediaReconnectStart,this.store.uid)),this.unbindLocalTrackEvents(),this.localTrackMap.clear(),0!==this.remoteUserMap.size&&Array.from(this.remoteUserMap.entries()).forEach((e=>{let[t,i]=e;Array.from(ph(i).call(i)).forEach((e=>{this.setPendingRemoteMedia(t,e)})),this.emit(hv.MediaReconnectStart,t.uid)})),this.unbindAllRemoteTrackEvents(),this.remoteUserMap.clear(),0!==this.localDataChannels.length&&(this.localDataChannels.forEach((e=>{this.pendingLocalDataChannels.push(e)})),this.localDataChannels.length=0),0!==this.remoteDataChannelMap.size&&(Array.from(this.remoteDataChannelMap.entries()).forEach((e=>{let[t,i]=e;Array.from(ph(i).call(i)).forEach((e=>{this.setPendingRemoteDataChannel(t,e)}))})),this.remoteDataChannelMap.clear()),this.statsUploader.stopUploadOutboundStats(),this.statsUploader.stopUploadInboundStats(),this.statsUploader.stopUploadTransportStats(),jC.debug(\"[\".concat(this.store.clientId,\"] P2PChannel disconnected, waiting to reconnect.\")))}hasPendingRemoteDataChannel(e,t){for(const i of this.pendingRemoteDataChannels){const{user:n,id:r}=i;if((e instanceof sV?e.uid:e)===n.uid&&r===t)return!0}return!1}setPendingRemoteDataChannel(e,t){this.hasPendingRemoteDataChannel(e,t)||this.pendingRemoteDataChannels.push({user:e,id:t})}hasPendingRemoteMedia(e,t){for(const i of this.pendingRemoteTracks){const{user:n,kind:r}=i;if((e instanceof sV?e.uid:e)===n.uid&&t===r)return!0}return!1}setPendingRemoteMedia(e,t){this.hasPendingRemoteMedia(e,t)||this.pendingRemoteTracks.push({user:e,kind:t})}restartICE(e){var t=this;return PU((function*(){if(!t.connection||t.state!==uv.Connected||t.connection instanceof iF)return;const i=yield IU(t.mutex.lock(\"From P2PChannel.restartICE\"));let n;try{n=yield IU(t.connection.restartICE(e));const r=yield IU(n.next());if(r.done)return;const s=r.value,o=yield s;switch(t.reportPCDisconnectedOrFailed(e),e){case cv.TCP:t._pcStatsUploadType=dv.TCP_RESTART;break;case cv.RELAY:t._pcStatsUploadType=dv.RELAY_RESTART;break;default:t._pcStatsUploadType=dv.OLD_RESTART}t._isInRestartIce=!0,n.next(o)}catch(e){var r;null===(r=n)||void 0===r||r.throw(e)}finally{i()}}))()}getUplinkNetworkQuality(){if(!this.connection)return 0;const e=this.connection.getStats(),t=this.localTrackMap.get(lv.LocalVideoTrack),i=this.localTrackMap.get(lv.LocalAudioTrack),n=e.videoSend.find((e=>e.ssrc===(null==t?void 0:t.ssrcs[0].ssrcId))),r=e.audioSend.find((e=>e.ssrc===(null==i?void 0:i.ssrcs[0].ssrcId)));if(!n||!r)return 1;const s=AT(this,hv.NeedSignalRTT),o=n?n.rttMs:void 0,a=r?r.rttMs:void 0,c=o&&a?(o+a)/2:o||a,d=(c&&s?(c+s)/2:c||s)||0,l=100*e.sendPacketLossRate*.7/50+.3*d/1500,u=l<.17?1:l<.36?2:l<.59?3:l<.1?4:5,h=null==t?void 0:t.track;if(h&&h._encoderConfig&&-1===h._hints.indexOf(jA.SCREEN_TRACK)){const t=h._encoderConfig.bitrateMax,i=e.bitrate.actualEncoded;if(t&&i){const e=(1e3*t-i)/(1e3*t);return nI[e<.15?0:e<.3?1:e<.45?2:e<.6?3:4][u]}}return u}getDownlinkNetworkQuality(){if(!this.connection)return 0;const e=this.connection.getStats();let t=0;return Array.from(this.remoteUserMap.entries()).forEach((i=>{let[n]=i;const r=n._audioSSRC,s=n._videoSSRC,o=e.audioRecv.find((e=>e.ssrc===r)),a=e.videoRecv.find((e=>e.ssrc===s));if(!o&&!a)return void(t+=1);const c=AT(this,hv.NeedSignalRTT),d=e.rtt,l=(d&&c?(d+c)/2:d||c)||0,u=o?o.jitterMs:void 0,h=e.recvPacketLossRate;let p=.7*h*100/50+.3*l/1500;u&&(p=.6*h*100/50+.2*l/1500+.2*u/400);t+=p<.1?1:p<.17?2:p<.36?3:p<.59?4:5})),this.remoteUserMap.size>0?Math.round(t/this.remoteUserMap.size):t}async muteLocalTrack(e){return new cg(((t,i)=>{this.handleMuteLocalTrack(e,t,i)}))}async replaceTrack(e,t){var i;if(jC.debug(\"[\".concat(this.store.clientId,\"] P2PChannel replaceTrack from [\").concat(e.getTrackId(),\"] to [\").concat(t.getTrackId(),\"]\")),!this.connection||this.state!==uv.Connected)return;const n=Array.from(this.localTrackMap.entries()).find((t=>{let[,{track:i}]=t;return e===i}));if(!n)return;const r=n[0];if(e!==t&&(this.unbindLocalTrackEvents([{track:e,type:r}]),this.bindLocalTrackEvents([{track:t,type:r}]),n[1].track=t),await(null===(i=this.connection)||void 0===i?void 0:i.replaceTrack(t,n[1].id)),this.isPlanB){const e=n[1];e.id=t._mediaStreamTrack.id,this.localTrackMap.set(r,e)}if(r===lv.LocalVideoTrack&&!RC(\"DISABLE_DUAL_STREAM_USE_ENCODING\")&&IA().supportDualStreamEncoding){const t=this.localTrackMap.get(lv.LocalVideoLowTrack);if(t){const i=e._mediaStreamTrack.clone();t.track._originMediaStreamTrack.stop(),t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i,await new cg(((e,i)=>{this.handleReplaceTrack(t.track,e,i,!0)}))}}}filterTobePublishedTracks(e,t,i){const n=[],r=this.getAllTracks();e=HT(e=e.filter((e=>-1===r.indexOf(e))));let s,o=!1;const a=this.localTrackMap.get(lv.LocalAudioTrack);for(const r of e){if(r instanceof Rw&&(this.localTrackMap.has(lv.LocalVideoTrack)||o?new Kg(Hg.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS).throw():(n.push({track:r,type:lv.LocalVideoTrack}),o=!0),t)){const e=this.getLowVideoTrack(r,i);n.push({track:e,type:lv.LocalVideoLowTrack})}if(r instanceof ew)if(a){const e=a.track;if(e instanceof nw)cV([r]),e.addAudioTrack(r),this.bindLocalAudioTrackEvents(r,!0);else{const t=dV([e,r]);jC.debug(\"[\".concat(this.store.clientId,\"] [p2pId: \").concat(this.store.p2pId,\"]: P2PConnection will replace audioTrack [\").concat(t.getTrackId(),\"]\")),this.replaceTrack(e,t)}}else if(s instanceof nw)cV([r]),s.addAudioTrack(r);else if(s||!r._useAudioElement&&IA().webAudioMediaStreamDest&&!r._bypassWebAudio){s=dV(s?[r,s]:[r])}else s=r}return s&&(jC.debug(\"[\".concat(this.store.clientId,\"] [p2pId: \").concat(this.store.p2pId,\"]: P2PConnection will send audioTrack [\").concat(s.getTrackId(),\"]\")),n.push({track:s,type:lv.LocalAudioTrack})),n}filterTobeUnpublishedTracks(e){const t=[],i=this.getAllTracks();e=HT(e=e.filter((e=>-1!==i.indexOf(e))));for(const i of e){if(i instanceof ew){const e=this.localTrackMap.get(lv.LocalAudioTrack);if(!e)continue;e.track instanceof nw?(e.track.removeAudioTrack(i),this.unbindLocalAudioTrackEvents(i),0===e.track.trackList.length&&(t.push([lv.LocalAudioTrack,e]),e.track.close())):t.push([lv.LocalAudioTrack,e])}if(i instanceof Rw){const e=this.localTrackMap.get(lv.LocalVideoTrack);if(!e)continue;t.push([lv.LocalVideoTrack,e]);const i=this.localTrackMap.get(lv.LocalVideoLowTrack);i&&t.push([lv.LocalVideoLowTrack,i])}}return t}filterTobePublishedDataChannels(e){return e=(e=HT(e)).filter((e=>-1===this.localDataChannels.findIndex((t=>t.id===e.id))))}filterTobeUnpublishedDataChannels(e){return e=(e=(e=HT(e)).filter((e=>-1!==this.localDataChannels.indexOf(e)))).filter((e=>e._originDataChannel))}bindLocalTrackEvents(e){e.forEach((e=>{let{track:t,type:i}=e;switch(i){case lv.LocalVideoTrack:t.addListener(BA.GET_STATS,this.handleGetLocalVideoStats),t.addListener(BA.GET_RTC_STATS,this.handleGetRTCStats),t.addListener(BA.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.addListener(BA.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.addListener(BA.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.addListener(BA.SET_OPTIMIZATION_MODE,this.handleSetOptimizationMode),t.addListener(BA.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.addListener(BA.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.addListener(BA.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case lv.LocalAudioTrack:this.bindLocalAudioTrackEvents(t);case lv.LocalVideoLowTrack:}}))}bindLocalAudioTrackEvents(e,t){e instanceof nw?e.trackList.forEach((e=>{e.addListener(BA.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(BA.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(BA.GET_STATS,this.handleGetLocalAudioStats),e.addListener(BA.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(BA.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)})):(e.addListener(BA.GET_STATS,this.handleGetLocalAudioStats),e.addListener(BA.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(BA.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(BA.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(BA.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack),t||(e.addListener(BA.NEED_REPLACE_TRACK,this.handleReplaceTrack),e.addListener(BA.NEED_REPLACE_MIXING_TRACK,this.handleReplaceMixingTrack)))}unbindLocalTrackEvents(e){e||(e=Array.from(this.localTrackMap.entries()).map((e=>{let[t,{track:i}]=e;return{track:i,type:t}}))),e.forEach((e=>{let{track:t,type:i}=e;switch(i){case lv.LocalVideoTrack:t.off(BA.GET_STATS,this.handleGetLocalVideoStats),t.off(BA.GET_RTC_STATS,this.handleGetRTCStats),t.off(BA.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.off(BA.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.off(BA.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.off(BA.SET_OPTIMIZATION_MODE,this.handleSetOptimizationMode),t.off(BA.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.off(BA.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.off(BA.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case lv.LocalAudioTrack:this.unbindLocalAudioTrackEvents(t);case lv.LocalVideoLowTrack:}}))}unbindLocalAudioTrackEvents(e){e instanceof nw?e.trackList.forEach((e=>{e.off(BA.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(BA.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(BA.GET_STATS,this.handleGetLocalAudioStats),e.off(BA.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(BA.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)})):(e.off(BA.GET_STATS,this.handleGetLocalAudioStats),e.off(BA.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(BA.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(BA.NEED_REPLACE_TRACK,this.handleReplaceTrack),e.off(BA.NEED_REPLACE_MIXING_TRACK,this.handleReplaceMixingTrack),e.off(BA.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(BA.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack))}bindRemoteTrackEvents(e,t){t instanceof Ow&&t.addListener(BA.GET_STATS,(t=>{t(this.handleGetRemoteVideoStats(e))})),t instanceof Nw&&t.addListener(BA.GET_STATS,(t=>{t(this.handleGetRemoteAudioStats(e))}))}unbindRemoteTrackEvents(e){e&&e.removeAllListeners(BA.GET_STATS)}unbindAllRemoteTrackEvents(){Array.from(this.remoteUserMap.entries()).forEach((e=>{let[t,i]=e;i.has(av.AUDIO)&&this.unbindRemoteTrackEvents(t._audioTrack),i.has(av.VIDEO)&&this.unbindRemoteTrackEvents(t._videoTrack)}))}createGatewayPublishMessage(e,t){return e.map(((e,i)=>{var n;let r,s,{track:o,type:a}=e;switch(a){case lv.LocalAudioTrack:r=JI.Audio,s={dtx:o instanceof tw&&o._config.DTX,hq:!1,lq:!1,stereo:!1,speech:!1};break;case lv.LocalVideoTrack:r=bn(n=o._hints).call(n,jA.SCREEN_TRACK)?JI.Screen:JI.High,s=sF(sF({},Ry(o)),{},{codec:this.store.codec});break;case lv.LocalVideoLowTrack:r=JI.Low,s=sF(sF({},Ry(o)),{},{codec:this.store.codec})}return{stream_type:r,attributes:s,ssrcs:t[i]}}))}createGatewayUnpublishMessage(e){return e.map((e=>{var t;let i,[n,{track:r,ssrcs:s,id:o}]=e;switch(n){case lv.LocalVideoTrack:i=bn(t=r._hints).call(t,jA.SCREEN_TRACK)?JI.Screen:JI.High;break;case lv.LocalAudioTrack:i=JI.Audio;break;case lv.LocalVideoLowTrack:i=JI.Low}return{stream_type:i,ssrcs:s,mid:o}}))}assignLocalTracks(e,t){e.forEach(((e,i)=>{let{track:n,type:r}=e;this.localTrackMap.set(r,{track:n,id:t[i].id,ssrcs:t[i].localSSRC})}))}withdrawLocalTracks(e){e.forEach((e=>{let[t]=e;this.localTrackMap.delete(t)}))}bindConnectionEvents(e){e.onConnectionStateChange=async t=>{if(jC.info(\"[\".concat(this.store.clientId,\"] [p2pId: \").concat(this.store.p2pId,\"]: P2PConnection.onConnectionStateChange(\").concat(t,\")\")),this.emit(hv.PeerConnectionStateChange,t),\"connected\"!==t||this.store.keyMetrics.peerConnectionEnd||this.store.peerConnectionEnd(),\"connected\"===t&&(this._restartTimer&&(clearTimeout(this._restartTimer),this._restartTimer=void 0),(this._isFirstConnected||this._isInRestartIce)&&this.reportPCStats(Date.now(),!0,this._pcStatsUploadType),this._isInRestartIce=!1,this._isFirstConnected=!1,this._isStartRestartIce=!1),RC(\"NEW_ICE_RESTART\")){var i;if(bn(i=this._restartStates).call(i,t)){if(this._isStartRestartIce)return;this._isStartRestartIce=!0;const t=t=>{if(\"disconnected\"===e.iceConnectionState||\"checking\"===e.iceConnectionState||\"failed\"===e.iceConnectionState){jC.debug(\"[\".concat(this.store.clientId,\"] [P2PChannel] start use restartICE, type is \").concat(t));\"CONNECTED\"===AT(this,hv.QueryClientConnectionState)&&this.emit(hv.RequestRestartICE,t)}},i=()=>{\"disconnected\"!==e.iceConnectionState&&\"checking\"!==e.iceConnectionState&&\"failed\"!==e.iceConnectionState||(this.reportPCStats(Date.now(),!1,this._pcStatsUploadType),jC.debug(\"[\".concat(this.store.clientId,\"] P2PConnection disconnected timeout, force reconnect\")),setTimeout((()=>this.emit(hv.P2PLost)),0),this.iceFailedCount+=1,this.requestReconnect())},n=RC(\"ICE_RESTART_INTERVAL\");return void(this._restartTimer=window.setTimeout((()=>{if(RC(\"JOIN_WITH_FALLBACK_MEDIA_PROXY_FORCE\")&&IA().supportPCSetConfiguration)t(cv.RELAY),this._restartTimer=window.setTimeout(i,n);else if(wg())t(cv.UDP),this._restartTimer=window.setTimeout(i,4e3);else{if(t(cv.TCP),IA().supportPCSetConfiguration)return void(this._restartTimer=window.setTimeout((()=>{t(cv.RELAY),this._restartTimer=window.setTimeout(i,n)}),n));this._restartTimer=window.setTimeout(i,n)}}),800))}}else{if(\"disconnected\"===t&&\"disconnected\"===e.iceConnectionState)return setTimeout((()=>{if(\"disconnected\"===e.iceConnectionState&&RC(\"ICE_RESTART\")){\"CONNECTED\"===AT(this,hv.QueryClientConnectionState)&&this.emit(hv.RequestRestartICE)}}),800),void setTimeout((()=>{\"disconnected\"===e.peerConnectionState&&(jC.debug(\"[\".concat(this.store.clientId,\"] [p2pId: \").concat(this.store.p2pId,\"]: P2PConnection disconnected timeout 4000ms, force reconnect\")),this.reportPCStats(Date.now(),!1,this._pcStatsUploadType),this._isInRestartIce=!1,setTimeout((()=>this.emit(hv.P2PLost)),0),this.iceFailedCount+=1,this.requestReconnect())}),4e3);\"failed\"===t&&(jC.debug(\"[\".concat(this.store.clientId,\"] [p2pId: \").concat(this.store.p2pId,\"]: P2PConnection state failed, force reconnect\")),this.reportPCDisconnectedOrFailed(),setTimeout((()=>this.emit(hv.P2PLost)),0),this.iceFailedCount+=1,await this.requestReconnect())}},e.onICEConnectionStateChange=e=>{\"connected\"!==e||this.store.keyMetrics.iceConnectionEnd||this.store.iceConnectionEnd(),jC.info(\"[\".concat(this.store.clientId,\"] [p2pId: \").concat(this.store.p2pId,\"]: P2PConnection.onICEConnectionStateChange(\").concat(e,\")\")),eI.reportApiInvoke(this.store.sessionId,{name:\"ICEConnectionStateChange\",options:e,tag:pT.TRACER}).onSuccess(),this.emit(hv.IceConnectionStateChange,e)},e.onICETransportStateChange=e=>{jC.info(\"[\".concat(this.store.clientId,\"] [p2pId: \").concat(this.store.p2pId,\"]: P2PConnection.onICETransportStateChange(\").concat(e,\")\"))},e.onDTLSTransportStateChange=e=>{jC.info(\"[\".concat(this.store.clientId,\"] [p2pId: \").concat(this.store.p2pId,\"]: P2PConnection.onDTLSTransportStateChange(\").concat(e,\")\"))},e.onDTLSTransportError=e=>{jC.info(\"[\".concat(this.store.clientId,\"] [p2pId: \").concat(this.store.p2pId,\"]: P2PConnection.onDTLSTransportError(\").concat(e,\")\"))},e.onFirstAudioDecoded=e=>{var t;const i=Array.from(ph(t=this.remoteUserMap).call(t)).find((t=>t._audioSSRC===e));var n;i&&(this.store.subscribe(i.uid,\"audio\",void 0,void 0,void 0,Date.now()),null===(n=i.audioTrack)||void 0===n||n.emit(qA.FIRST_FRAME_DECODED),eI.firstRemoteFrame(this.store.sessionId,YC.FIRST_AUDIO_DECODE,qC.FIRST_AUDIO_DECODE,{peer:i._uintid,subscribeElapse:RU.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId}))},e.onFirstAudioReceived=e=>{var t;const i=Array.from(ph(t=this.remoteUserMap).call(t)).find((t=>t._audioSSRC===e));i&&eI.firstRemoteFrame(this.store.sessionId,YC.FIRST_AUDIO_RECEIVED,qC.FIRST_AUDIO_RECEIVED,{peer:i._uintid,subscribeElapse:RU.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId})},e.onFirstVideoDecoded=(e,t,i)=>{this.reportVideoFirstFrameDecoded(e,t,i)},e.onFirstVideoReceived=e=>{var t;const i=Array.from(ph(t=this.remoteUserMap).call(t)).find((t=>t._videoSSRC===e));i&&eI.firstRemoteFrame(this.store.sessionId,YC.FIRST_VIDEO_RECEIVED,qC.FIRST_VIDEO_RECEIVED,{peer:i._uintid,subscribeElapse:RU.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId})},e.onSelectedLocalCandidateChanged=(e,t)=>{const i=\"relay\"===e.candidateType,n=\"relay\"===t.candidateType;\"unknown\"!==t.candidateType&&i===n||this.emit(hv.ConnectionTypeChange,i),jC.info(\"[\".concat(this.store.clientId,\"] [p2pId: \").concat(this.store.p2pId,\"]: P2PConnection.SelectedLocalCandidateChanged(\").concat(JSON.stringify(Ay(t)),\" -> \").concat(JSON.stringify(Ay(e)),\")\"))},e.onSelectedRemoteCandidateChanged=(e,t)=>{jC.info(\"[\".concat(this.store.clientId,\"] [p2pId: \").concat(this.store.p2pId,\"]: P2PConnection.SelectedRemoteCandidateChanged(\").concat(JSON.stringify(Ay(t)),\" -> \").concat(JSON.stringify(Ay(e)),\")\"))},e.onFirstVideoDecodedTimeout=e=>{this.reportVideoFirstFrameDecoded(e,void 0,void 0,!0)}}unbindConnectionEvents(e){e.onConnectionStateChange=void 0,e.onICEConnectionStateChange=void 0,e.onICETransportStateChange=void 0,e.onDTLSTransportStateChange=void 0,e.onDTLSTransportError=void 0,e.onFirstAudioDecoded=void 0,e.onFirstAudioReceived=void 0,e.onFirstVideoDecoded=void 0,e.onFirstVideoReceived=void 0,e.onSelectedLocalCandidateChanged=void 0,e.onSelectedRemoteCandidateChanged=void 0,e.onFirstVideoDecodedTimeout=void 0}filterTobeMutedTracks(e){const t=[];if(-1===this.getAllTracks().indexOf(e))return t;const i=this.localTrackMap.get(lv.LocalAudioTrack);if(e instanceof ew&&(null==i?void 0:i.track)instanceof nw)return i.track.isActive||t.push([lv.LocalAudioTrack,i]),t;const n=Array.from(this.localTrackMap.entries()).find((t=>{let[,{track:i}]=t;return e===i}));if(n&&(t.push(n),n[0]===lv.LocalVideoTrack)){const e=this.localTrackMap.get(lv.LocalVideoLowTrack);e&&t.push([lv.LocalVideoLowTrack,e])}return t}filterTobeUnmutedTracks(e){const t=[],i=this.localTrackMap.get(lv.LocalAudioTrack);if(e instanceof ew&&(null==i?void 0:i.track)instanceof nw)return i.track.isActive&&t.push([lv.LocalAudioTrack,i]),t;const n=Array.from(this.localTrackMap.entries()).find((t=>{let[,{track:i}]=t;return e===i}));if(n)if(n[0]===lv.LocalVideoTrack){t.push(n);const e=this.localTrackMap.get(lv.LocalVideoLowTrack);e&&t.push([lv.LocalVideoLowTrack,e])}else t.push(n);return t}createMuteMessage(e){return e.map((e=>{var t;let i,[n,{track:r,ssrcs:s,id:o}]=e;switch(n){case lv.LocalAudioTrack:i=JI.Audio;break;case lv.LocalVideoTrack:i=bn(t=r._hints).call(t,jA.SCREEN_TRACK)?JI.Screen:JI.High;break;case lv.LocalVideoLowTrack:i=JI.Low}return{stream_type:i,ssrcs:s,mid:o}}))}createUnmuteMessage(e){return e.map((e=>{var t;let i,[n,{track:r,ssrcs:s,id:o}]=e;switch(n){case lv.LocalAudioTrack:i=JI.Audio;break;case lv.LocalVideoTrack:i=bn(t=r._hints).call(t,jA.SCREEN_TRACK)?JI.Screen:JI.High;break;case lv.LocalVideoLowTrack:i=JI.Low}return{stream_type:i,ssrcs:s,mid:o}}))}filterTobeUnSubscribedTracks(e,t){const i=[],n=this.remoteUserMap.get(e);if(!n)return i;if(t){const r=n.get(t);if(!r)return i;i.push([e,{kind:t,id:r}])}else Array.from(n.entries()).forEach((t=>{let[n,r]=t;i.push([e,{kind:n,id:r}])}));return i}filterTobeUnSubscribedDataChannels(e,t){const i=[];return t.forEach((t=>{var n;null!==(n=this.remoteDataChannelMap.get(e))&&void 0!==n&&n.has(t.id)&&i.push(t)})),i}createUnsubscribeMessage(e){const t=[];return e.forEach((e=>{let[i,{kind:n,id:r}]=e;switch(n){case av.VIDEO:return void(i._videoSSRC&&t.push({stream_type:av.VIDEO,ssrcId:i._videoSSRC}));case av.AUDIO:return void(i._audioSSRC&&t.push({stream_type:av.AUDIO,ssrcId:i._audioSSRC}))}})),t}createUnsubscribeAllMessage(e){const t=new Map;return e.forEach((e=>{let[i,{kind:n}]=e;if(t.has(i)){let e=t.get(i);n===av.VIDEO?e|=ZI.Video:e|=ZI.Audio,t.set(i,e)}else n===av.VIDEO?t.set(i,ZI.Video):t.set(i,ZI.Audio)})),{users:Array.from(t.entries()).map((e=>{let[t,i]=e;return{stream_id:t.uid,stream_type:i}}))}}withdrawRemoteTracks(e){e.forEach((e=>{let[t,{kind:i}]=e;const n=this.remoteUserMap.get(t);n&&(n.delete(i),0===Array.from(n.entries()).length&&this.remoteUserMap.delete(t))}))}async updateBitrateLimit(e){const t=this.localTrackMap.get(lv.LocalVideoTrack),i=this.localTrackMap.get(lv.LocalVideoLowTrack);t&&await t.track.setBitrateLimit(e.uplink),i&&e.low_stream_uplink&&await i.track.setBitrateLimit({max_bitrate:e.low_stream_uplink.bitrate,min_bitrate:e.low_stream_uplink.bitrate||0})}isP2PDisconnected(){if(this.connection){return\"connected\"!==this.connection.peerConnectionState}return!0}mapPubResToRemoteConfig(e,t){return e.map(((e,i)=>{var n;let{stream_type:r}=e;return null===(n=t.find((e=>{let{stream_type:t}=e;return r===t})))||void 0===n?void 0:n.attributes}))}async tryToUnmuteAudio(e){for(let i=0;i{let[,{id:t}]=e;return t}))));const r=this.createUnmuteMessage(n);return void await yT(this,hv.RequestUnmuteLocal,r)}}bindStatsUploaderEvents(){this.statsUploader.requestStats=()=>this.getStats(),this.statsUploader.requestLocalMedia=()=>Array.from(this.localTrackMap.entries()),this.statsUploader.requestRemoteMedia=()=>Array.from(this.remoteUserMap.entries()),this.statsUploader.requestVideoIsReady=e=>{var t;return!(null===(t=this.connection)||void 0===t||!t.getRemoteVideoIsReady(e))},this.statsUploader.requestUpload=(e,t)=>this.emit(hv.RequestUpload,e,t),this.statsUploader.requestUploadStats=e=>this.emit(hv.RequestUploadStats,e),this.statsUploader.requestAllTracks=()=>this.getAllTracks()}unbindStatsUploaderEvents(){this.statsUploader.requestStats=void 0,this.statsUploader.requestLocalMedia=void 0,this.statsUploader.requestRemoteMedia=void 0,this.statsUploader.requestVideoIsReady=void 0}async requestReconnect(){this.dtlsFailedCount+=1,await iS(mS(this.dtlsFailedCount,ES)),this.emit(hv.RequestReconnect)}async reconnectP2P(){const e=Array.from(this.localTrackMap.entries()),t=this.createGatewayUnpublishMessage(e);Array.from(this.remoteUserMap.entries()),t.length>0&&await vT(this,hv.RequestUnpublishForReconnectPC,t),this.disconnectForReconnect(),this.emit(hv.RequestReconnectPC)}canPublishLowStream(){return this.localTrackMap.has(lv.LocalVideoTrack)||this.pendingLocalTracks.some((e=>e instanceof Rw))}throwIfTrackTypeNotMatch(e){if(e.filter((e=>e instanceof Rw)).length>1)throw new Kg(Hg.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(e.filter((e=>e instanceof ew)).length>1&&(e.some((e=>e instanceof ew&&e._bypassWebAudio))||!IA().webAudioMediaStreamDest))throw new Kg(Hg.NOT_SUPPORTED,\"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode\");for(const t of e){if(t instanceof Rw&&this.pendingLocalTracks.some((e=>e instanceof Rw)))throw new Kg(Hg.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(t instanceof ew&&this.pendingLocalTracks.some((e=>e instanceof ew))&&(!IA().webAudioMediaStreamDest||t._bypassWebAudio||this.pendingLocalTracks.some((e=>e instanceof ew&&e._bypassWebAudio))))throw new Kg(Hg.NOT_SUPPORTED,\"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode\")}}getLowVideoTrack(e,t){const i=!RC(\"DISABLE_DUAL_STREAM_USE_ENCODING\")&&IA().supportDualStreamEncoding,n=sF(sF({},{width:160,height:120,framerate:15,bitrate:50}),t);let r;r=i?e._mediaStreamTrack.clone():Gx(e,n);const s=nS(8,\"track-low-\"),o=new Rw(r,sF(sF({},i&&{scaleResolutionDownBy:yy(n,e)}),{},{frameRate:n.framerate,bitrateMax:n.bitrate,bitrateMin:n.bitrate}),void 0,void 0,s);return o.on(KA.TRANSCEIVER_UPDATED,(t=>{e._updateRtpTransceiver(t,GA.LOW_STREAM)})),o._hints.push(jA.LOW_STREAM),e.on(\"sei-to-send\",(e=>{o.emit(\"sei-to-send\",e)})),e.addListener(BA.NEED_CLOSE,(()=>{o.close()})),o}async globalLock(){return this.mutex.lock(\"From P2PChannel.globalLock\")}async reportPCStats(e,t,i){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null;if(this.connection&&this.connection instanceof jV){var r,s,o,a;const c=this.store.keyMetrics.descriptionStart||0,{iceConnectionState:d,dtlsTransportState:l,peerConnectionState:u}=this.connection,{local:h,remote:p}=await this.connection.getSelectedCandidatePair();eI.pcStats(this.store.sessionId,{startTime:c,eventElapse:e-c||0,iceconnectionsate:d,dtlsstate:l,connectionstate:u,intSucc:t?1:2,error:n,selectedLocalCandidateProtocol:null!==(r=null==h?void 0:h.protocol)&&void 0!==r?r:\"\",selectedLocalCandidateType:null!==(s=h.candidateType)&&void 0!==s?s:\"\",selectedLocalCandidateAddress:\"\".concat(h.address,\":\").concat(h.port),selectedRemoteCandidateProtocol:null!==(o=p.protocol)&&void 0!==o?o:\"\",selectedRemoteCandidateType:null!==(a=p.candidateType)&&void 0!==a?a:\"\",selectedRemoteCandidateAddress:\"\".concat(p.address,\":\").concat(p.port),restartCnt:i})}}reportVideoFirstFrameDecoded(e,t,i,n){var r;const s=Array.from(ph(r=this.remoteUserMap).call(r)).find((t=>t._videoSSRC===e));if(s){n||this.store.subscribe(s.uid,\"video\",void 0,void 0,void 0,void 0,Date.now());const r=this.store.keyMetrics,o=r.subscribe.find((e=>e.userId===s.uid&&\"video\"===e.type));eI.firstRemoteVideoDecode(this.store.sessionId,YC.FIRST_VIDEO_DECODE,qC.FIRST_VIDEO_DECODE,{peer:s._uintid,videowidth:t,videoheight:i,subscribeElapse:RU.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId,apEnd:r.requestAPEnd||0,apStart:r.requestAPStart||0,joinGwEnd:r.joinGatewayEnd||0,joinGwStart:r.joinGatewayStart||0,pcEnd:r.peerConnectionEnd||0,pcStart:r.peerConnectionStart||0,subscriberEnd:(null==o?void 0:o.subscribeEnd)||0,subscriberStart:(null==o?void 0:o.subscribeStart)||0,videoAddNotify:(null==o?void 0:o.streamAdded)||0,state:n?1:0})}}async remoteMediaSsrcChanged(e,t,i){if(!this.connection)return!1;const n=this.remoteUserMap.get(e);if(!n)return!1;const r=n.get(t);if(!r)return!1;const s=await this.connection.getRemoteSSRC(r);return void 0!==s&&s!==i}resetConnection(e){jC.debug(\"[\".concat(this.store.clientId,\"] [P2PChannel] reset connection to \").concat(e)),this.state===uv.Connected?(jC.debug(\"[\".concat(this.store.clientId,\"] [P2PChannel] fallback to websocket but P2PChannel state still connected, disconnect first\")),this.disconnectForReconnect()):(this.connection&&(this.connection.close(),this.unbindConnectionEvents(this.connection),this.connection=void 0),this.shouldForwardP2PCreation&&(this.connection=e===$I.datachannel?new iF({},this.store):this.isPlanB?new LV({},this.store):new jV({},this.store),this.bindConnectionEvents(this.connection)))}unbindRtpTransceiver(){0!==this.localTrackMap.size&&Array.from(this.localTrackMap.entries()).forEach((e=>{let[t,{track:i}]=e;t===lv.LocalVideoLowTrack?i._updateRtpTransceiver(void 0,GA.LOW_STREAM):i._updateRtpTransceiver(void 0)}))}reportPCDisconnectedOrFailed(e){this.connection&&this.connection instanceof jV&&(\"disconnected\"!==this.connection.iceConnectionState&&\"checking\"!==this.connection.iceConnectionState&&\"failed\"!==this.connection.iceConnectionState||(this._isFirstConnected?(this.reportPCStats(Date.now(),!1,this._pcStatsUploadType),this._isFirstConnected=!1):this._pcStatsUploadType===dv.TCP_RESTART&&e===cv.RELAY?this.reportPCStats(Date.now(),!1,this._pcStatsUploadType):this.reportPCStats(Date.now(),!1,dv.DISCONNECTED_OR_FAILED)))}}function dF(e,t,i){const n=e[t];if(\"function\"!=typeof n)throw new Error(\"Cannot use mutex on object property.\");return i.value=async function(){const e=this.mutex,i=await e.lock(\"From P2PChannel.\".concat(t));try{for(var r=arguments.length,s=new Array(r),o=0;o>>3){case 0:break e;case 1:t.code=kF(e);break;case 2:t.msg=bF(e,kF(e));break;case 3:{let i=_F(e);t.data=hF(e),e.limit=i;break}default:EF(e,7&i)}}return t}({bytes:t=e,offset:0,limit:t.length});var t}function hF(e){let t={};e:for(;!vF(e);){let i=kF(e);switch(i>>>3){case 0:break e;case 1:t.requestId=bF(e,kF(e));break;case 2:t.requestType=kF(e)>>>0;break;case 3:t.scorePorn=PF(e);break;case 4:t.scoreSexy=PF(e);break;case 5:t.scoreNeutral=PF(e);break;case 6:t.requestScene=kF(e)>>>0;break;case 7:t.scene=kF(e)>>>0;break;default:EF(e,7&i)}}return t}function pF(e,t){let i=e.service;void 0!==i&&(MF(t,8),MF(t,i));let n=e.vendor;void 0!==n&&(MF(t,16),MF(t,n));let r=e.token;void 0!==r&&(MF(t,26),wF(t,r));let s=e.callbackUrl;void 0!==s&&(MF(t,34),wF(t,s))}function _F(e){let t=kF(e),i=e.limit;return e.limit=e.offset+t,i}function EF(e,t){switch(t){case 0:for(;128&NF(e););break;case 2:IF(e,kF(e));break;case 5:IF(e,4);break;case 1:IF(e,8);break;default:throw new Error(\"Unimplemented type: \"+t)}}DI([dF,PI(\"design:type\",Function),PI(\"design:paramtypes\",[Object,Boolean]),PI(\"design:returntype\",cg)],cF.prototype,\"startP2PConnection\",null),DI([dF,PI(\"design:type\",Function),PI(\"design:paramtypes\",[Object,Object,Array,Object,String,String]),PI(\"design:returntype\",cg)],cF.prototype,\"connect\",null),DI([dF,PI(\"design:type\",Function),PI(\"design:paramtypes\",[Array]),PI(\"design:returntype\",void 0)],cF.prototype,\"updateRemoteRTPCapabilities\",null),DI([dF,PI(\"design:type\",Function),PI(\"design:paramtypes\",[Object,Object,Array,Object,String,String]),PI(\"design:returntype\",cg)],cF.prototype,\"preConnect\",null),DI([dF,PI(\"design:type\",Function),PI(\"design:paramtypes\",[Array]),PI(\"design:returntype\",cg)],cF.prototype,\"publishDataChannel\",null),DI([dF,PI(\"design:type\",Function),PI(\"design:paramtypes\",[Array]),PI(\"design:returntype\",cg)],cF.prototype,\"unpublish\",null),DI([dF,PI(\"design:type\",Function),PI(\"design:paramtypes\",[Array]),PI(\"design:returntype\",cg)],cF.prototype,\"unpublishDataChannel\",null),DI([dF,PI(\"design:type\",Function),PI(\"design:paramtypes\",[]),PI(\"design:returntype\",cg)],cF.prototype,\"unpublishLowStream\",null),DI([dF,PI(\"design:type\",Function),PI(\"design:paramtypes\",[sV,Array]),PI(\"design:returntype\",cg)],cF.prototype,\"subscribeDataChannel\",null),DI([dF,PI(\"design:type\",Function),PI(\"design:paramtypes\",[sV,String,Number,Number,Array]),PI(\"design:returntype\",cg)],cF.prototype,\"subscribe\",null),DI([dF,PI(\"design:type\",Function),PI(\"design:paramtypes\",[Array]),PI(\"design:returntype\",cg)],cF.prototype,\"massSubscribe\",null),DI([dF,PI(\"design:type\",Function),PI(\"design:paramtypes\",[sV,String,Boolean]),PI(\"design:returntype\",cg)],cF.prototype,\"unsubscribe\",null),DI([dF,PI(\"design:type\",Function),PI(\"design:paramtypes\",[sV,Array]),PI(\"design:returntype\",cg)],cF.prototype,\"unsubscribeDataChannel\",null),DI([dF,PI(\"design:type\",Function),PI(\"design:paramtypes\",[Array]),PI(\"design:returntype\",cg)],cF.prototype,\"massUnsubscribe\",null),DI([dF,PI(\"design:type\",Function),PI(\"design:paramtypes\",[sV,String]),PI(\"design:returntype\",cg)],cF.prototype,\"muteRemote\",null),DI([dF,PI(\"design:type\",Function),PI(\"design:paramtypes\",[sV,String]),PI(\"design:returntype\",cg)],cF.prototype,\"unmuteRemote\",null),DI([dF,PI(\"design:type\",Function),PI(\"design:paramtypes\",[sV,String]),PI(\"design:returntype\",cg)],cF.prototype,\"hasRemoteMediaWithLock\",null),DI([dF,PI(\"design:type\",Function),PI(\"design:paramtypes\",[]),PI(\"design:returntype\",cg)],cF.prototype,\"disconnectForReconnect\",null),DI([dF,PI(\"design:type\",Function),PI(\"design:paramtypes\",[Object]),PI(\"design:returntype\",cg)],cF.prototype,\"updateBitrateLimit\",null),DI([dF,PI(\"design:type\",Function),PI(\"design:paramtypes\",[sV,String,Number]),PI(\"design:returntype\",cg)],cF.prototype,\"remoteMediaSsrcChanged\",null);let mF=new Float32Array(1);new Uint8Array(mF.buffer);let fF=new Float64Array(1),gF=new Uint8Array(fF.buffer);function TF(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}let SF=[];function RF(){const e=SF.pop();return e?(e.offset=e.limit=0,e):{bytes:new Uint8Array(64),offset:0,limit:0}}function CF(e){SF.push(e)}function IF(e,t){if(e.offset+t>e.limit)throw new Error(\"Skip past limit\");e.offset+=t}function vF(e){return e.offset>=e.limit}function yF(e,t){let i=e.bytes,n=e.offset,r=e.limit,s=n+t;if(s>i.length){let t=new Uint8Array(2*s);t.set(i),e.bytes=t}return e.offset=s,s>r&&(e.limit=s),n}function AF(e,t){let i=e.offset;if(i+t>e.limit)throw new Error(\"Read past limit\");return e.offset+=t,i}function bF(e,t){let i=AF(e,t),n=String.fromCharCode,r=e.bytes,s=\"\uFFFD\",o=\"\";for(let e=0;e=t?o+=s:(a=r[e+i+1],128!=(192&a)?o+=s:(l=(31&u)<<6|63&a,l<128?o+=s:(o+=n(l),e++))):224==(240&u)?e+2>=t?o+=s:(a=r[e+i+1],c=r[e+i+2],32896!=(49344&(a|c<<8))?o+=s:(l=(15&u)<<12|(63&a)<<6|63&c,l<2048||l>=55296&&l<=57343?o+=s:(o+=n(l),e+=2))):240==(248&u)?e+3>=t?o+=s:(a=r[e+i+1],c=r[e+i+2],d=r[e+i+3],8421504!=(12632256&(a|c<<8|d<<16))?o+=s:(l=(7&u)<<18|(63&a)<<12|(63&c)<<6|63&d,l<65536||l>1114111?o+=s:(l-=65536,o+=n(55296+(l>>10),56320+(1023&l)),e+=3))):o+=s}return o}function wF(e,t){let i=t.length,n=0;for(let e=0;e=55296&&r<=56319&&e+1=55296&&n<=56319&&e+1>6&31|192:(n<65536?s[r++]=n>>12&15|224:(s[r++]=n>>18&7|240,s[r++]=n>>12&63|128),s[r++]=n>>6&63|128),s[r++]=63&n|128)}}function OF(e,t){let i=yF(e,t.limit),n=e.bytes,r=t.bytes;for(let e=0,s=t.limit;e>>=0;t>=128;)DF(e,127&t|128),t>>>=7;DF(e,t)}function UF(e,t){let i=t.low>>>0,n=(t.low>>>28|t.high<<4)>>>0,r=t.high>>>24,s=0===r?0===n?i<16384?i<128?1:2:i<1<<21?3:4:n<16384?n<128?5:6:n<1<<21?7:8:r<128?9:10,o=yF(e,s),a=e.bytes;switch(s){case 10:a[o+9]=r>>>7&1;case 9:a[o+8]=9!==s?128|r:127&r;case 8:a[o+7]=8!==s?n>>>21|128:n>>>21&127;case 7:a[o+6]=7!==s?n>>>14|128:n>>>14&127;case 6:a[o+5]=6!==s?n>>>7|128:n>>>7&127;case 5:a[o+4]=5!==s?128|n:127&n;case 4:a[o+3]=4!==s?i>>>21|128:i>>>21&127;case 3:a[o+2]=3!==s?i>>>14|128:i>>>14&127;case 2:a[o+1]=2!==s?i>>>7|128:i>>>7&127;case 1:a[o]=1!==s?128|i:127&i}}function xF(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}const VF=new Map([[\"moderation\",1],[\"supervise\",2]]);class FF extends dT{get connectionState(){return this._connectionState}set connectionState(e){if(this._connectionState===e)return;const t=this._connectionState;this._connectionState=e,this.emit(mv.CONNECTION_STATE_CHANGE,t,e)}get inspectType(){return this._inspectType}set inspectType(e){var t;this._inspectMode=BT(t=e.map((e=>VF.get(e)||0))).call(t,((e,t)=>e+t)),this._inspectType=e}get quality(){return this._quality}set quality(e){this._quality=e>1?1:e<.1?.1:e,this.qualityTimer&&(window.clearTimeout(this.qualityTimer),this.qualityTimer=null),this._quality>=1||(this.qualityTimer=window.setTimeout((()=>{this.quality=this._quality/this.qualityRatio}),6e4))}constructor(e){super(),sh(this,\"name\",\"AgoraRTCVideoContentInspect\"),sh(this,\"_connectionState\",_v.CONNECTING),sh(this,\"_innerConnectionState\",void 0),sh(this,\"sequence\",0),sh(this,\"inspectStartTime\",void 0),sh(this,\"workerManagerConnection\",void 0),sh(this,\"workerConnection\",void 0),sh(this,\"workerMessageLengthLimit\",void 0),sh(this,\"inspectIntervalMinimum\",void 0),sh(this,\"qualityRatio\",void 0),sh(this,\"_connectInfo\",void 0),sh(this,\"_cancelTokenSource\",sC.CancelToken.source()),sh(this,\"_retryConfig\",void 0),sh(this,\"wmSequence\",0),sh(this,\"inspectInterval\",void 0),sh(this,\"inspectTimer\",null),sh(this,\"ossFilePrefix\",void 0),sh(this,\"extraInfo\",void 0),sh(this,\"_inspectType\",void 0),sh(this,\"_inspectMode\",void 0),sh(this,\"_quality\",1),sh(this,\"qualityTimer\",null),sh(this,\"_inspectId\",void 0),sh(this,\"_needWorkUrlOnly\",!1),sh(this,\"inspectImage\",(()=>{if(this.connectionState!==_v.CONNECTED)throw new LI(Hg.OPERATION_ABORTED,\"content inspect service connection status is \".concat(this.connectionState));this.inspectTimer&&(window.clearInterval(this.inspectTimer),this.inspectTimer=null),this.inspectTimer=window.setInterval((()=>{this.connectionState===_v.CONNECTED?this.requestToInspectImage():jC.debug(\"[\".concat(this._inspectId,\"] Inspect State is not connected , \"),this.connectionState)}),this.inspectInterval{this._innerConnectionState=e,jC.debug(\"[\".concat(this._inspectId,\"] Inspect operation :\").concat(Ev[e],\" \").concat(t||\"\"))})),this.handleWorkerManagerEvents(),this.workerConnection=new zv(\"worker-\"+this._inspectId,ES),this.handleWorkerEvents()}async init(e,t){this.emit(mv.STATE_CHANGE,Ev.CONNECT_AP),this._connectInfo=e;const i=this._cancelTokenSource.token;return this._retryConfig=t,new cg(((n,r)=>{this.on(mv.CONNECTION_STATE_CHANGE,((e,t)=>{t===_v.CONNECTED&&n()})),this.requestAP(e,i,t).then((e=>{this.connectWorkerManager(e)})).catch((e=>{r(e)}))}))}async requestAP(e,t,i){const n=RC(\"WEBCS_DOMAIN\").map((e=>\"https://\".concat(e,\"/api/v1\"))),r=await function(e,t,i,n){let{appId:r,areaCode:s,cname:o,sid:a,token:c,uid:d}=t;cA++;const l=\"image_moderation_api\",u={service_name:l,json_body:JSON.stringify({appId:r,areaCode:s,cname:o,command:\"allocateEdge\",requestId:cA,seq:cA,sid:a,token:c,ts:Date.now(),uid:d+\"\"})};let h,p,_=e[0];return fS((async()=>{h=Date.now();const e=await By(_,{data:u,cancelToken:i,headers:{\"X-Packet-Service-Type\":\"0\",\"X-Packet-URI\":\"61\"},params:{action:\"wrtc_gateway\"}});if(p=Date.now()-h,0!==e.code){const t=new LI(Hg.UNEXPECTED_RESPONSE,\"image inspect ap error, code\"+e.code,{retry:!0,responseTime:p});throw jC.error(t.toString()),t}const t=JSON.parse(e.json_body);if(200!==t.code){const e=new LI(Hg.UNEXPECTED_RESPONSE,\"image inspect ap error, code: \".concat(t.code,\", reason: \").concat(t.reason),{code:t.code,responseTime:p});throw jC.error(e.toString()),e}if(!t.servers||!Array.isArray(t.servers)||0===t.servers.length){const e=new LI(Hg.UNEXPECTED_RESPONSE,\"image inspect ap empty server\",{code:t.code,responseTime:p});throw jC.error(e.toString()),e}const n=RC(\"VIDEO_INSPECT_WORKER_MANAGER_HOST\"),r=RC(\"VIDEO_INSPECT_WORKER_MANAGER_PORT\");return{addressList:t.servers.map((e=>{let{address:t,wss:i}=e;if(t&&i)return\"wss://\".concat(t.replace(/\\./g,\"-\"),\".\").concat(n,\":\").concat(r||i)})).filter((e=>!!e)),workerToken:t.workerToken,vid:t.vid,responseTime:p}}),((t,i)=>(eI.apworkerEvent(a,{success:!0,sc:200,serviceName:l,responseDetail:JSON.stringify(t.addressList),firstSuccess:0===i,responseTime:p,serverIp:e[i%e.length]}),!1)),((t,i)=>(eI.apworkerEvent(a,{success:!1,sc:t.data&&t.data.code||200,serviceName:l,responseTime:p,serverIp:e[i%e.length]}),!!(t.code!==Hg.OPERATION_ABORTED&&t.code!==Hg.UNEXPECTED_RESPONSE||t.data&&t.data.retry)&&(_=e[(i+1)%e.length],!0))),n)}(n,e,t,i);this.emit(mv.STATE_CHANGE,Ev.AP_CONNECTED);const{addressList:s}=r;return this.wmSequence++,s}async connectWorkerManager(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this._needWorkUrlOnly=t,this.emit(mv.STATE_CHANGE,Ev.CONNECT_WORKER_MANAGER),await this.workerManagerConnection.init(e,1e4)}async connectWorker(e){await this.workerConnection.init([e])}handleWorkerManagerEvents(){this.workerManagerConnection.on(SI.CONNECTED,(async()=>{this.emit(mv.STATE_CHANGE,Ev.WORKER_MANAGER_CONNECTED,this.workerManagerConnection.url),this.workerManagerConnection.sendMessage({appId:this._connectInfo.appId,cname:this._connectInfo.cname,uid:this._connectInfo.uid+\"\",sdkVersion:\"4.20.2\",sid:this._connectInfo.sid,seq:this.wmSequence,ts:Number(Date.now()),requestId:Math.floor(1e12*Math.random()),allocate:!0,clientRequest:{command:\"join\"}},!0)})),this.workerManagerConnection.on(SI.CLOSED,(()=>{this._innerConnectionState{this._innerConnectionState{this._innerConnectionState{this.emit(mv.STATE_CHANGE,Ev.GET_WORKER_MANAGER_RESPONSE);const t=this.workerManagerConnection.url;this.workerManagerConnection.close();const i=JSON.parse(e.data);if(200!==i.code)throw jC.error(\"[\".concat(this._inspectId,\"] Unexpected code \").concat(i.code,\" from worker manager\")),new LI(Hg.UNEXPECTED_RESPONSE,\"response code of worker is unexpected\",i);if(!(i.serverResponse&&i.serverResponse.portWss&&t))throw jC.error(\"[\".concat(this._inspectId,\"] Unexpected content from worker manager : \").concat(JSON.stringify(i))),new LI(Hg.UNEXPECTED_RESPONSE,\"response content of worker is unexpected\",i);{const e=RC(\"VIDEO_INSPECT_WORKER_PORT\")||i.serverResponse.portWss,n=t.replace(/:\\d+\\/?$/,\":\".concat(e));this.emit(mv.STATE_CHANGE,Ev.CONNECT_WORKER,n),this._needWorkUrlOnly?this.emit(mv.REQUEST_NEW_WORKER_URL,n):await this.connectWorker(n)}})),this.workerManagerConnection.on(SI.WILL_RECONNECT,((e,t,i)=>{i(e)})),this.workerManagerConnection.on(SI.REQUEST_NEW_URLS,((e,t)=>{this.requestAP(this._connectInfo,this._cancelTokenSource.token,this._retryConfig).then(e).catch(t)}))}handleWorkerEvents(){this.workerConnection.on(SI.CONNECTED,(async()=>{this.emit(mv.STATE_CHANGE,Ev.WORKER_CONNECTED,this.workerConnection.url),this.connectionState=_v.CONNECTED})),this.workerConnection.on(SI.ON_MESSAGE,(async e=>{if(e.data instanceof ArrayBuffer){const i=uF(new Uint8Array(e.data));if(RC(\"SHOW_VIDEO_INSPECT_WORKER_MESSAGE\")&&jC.debug(\"[\".concat(this._inspectId,\"] Response message for worker of inspect content \"),JSON.stringify(i)),200===i.code){if(Array.isArray(this.inspectType)&&1===this.inspectType.length&&\"supervise\"===this.inspectType[0])return void this.emit(mv.INSPECT_RESULT,void 0,void 0);if(i.data&&i.data.scorePorn&&i.data.scoreSexy&&i.data.scoreNeutral){var t;const e={porn:i.data.scorePorn,sexy:i.data.scoreSexy,neutral:i.data.scoreNeutral},n=BT(t=Object.keys(e)).call(t,((t,i)=>e[t]>e[i]?t:i),\"porn\"),r=Object.keys(e).find((e=>e===n));this.emit(mv.INSPECT_RESULT,r)}else this.emit(mv.INSPECT_RESULT,void 0,new LI(Hg.UNEXPECTED_RESPONSE,i.code+\"\",\"There is an unexpected data on message\"))}else this.emit(mv.INSPECT_RESULT,void 0,new LI(Hg.UNEXPECTED_RESPONSE,i.code+\"\",i.msg))}else jC.error(\"[\".concat(this._inspectId,\"] Unexpected message type from worker\")),this.emit(mv.INSPECT_RESULT,void 0,new LI(Hg.UNEXPECTED_RESPONSE,\"invalid worker message type\"))})),this.workerConnection.on(SI.CLOSED,(()=>{this.connectionState=_v.CLOSED})),this.workerConnection.on(SI.FAILED,(()=>{this.connectionState=_v.CLOSED})),this.workerConnection.on(SI.RECONNECTING,(()=>{this.connectionState=this.connectionState===_v.CONNECTED?_v.RECONNECTING:_v.CONNECTING})),this.workerConnection.on(SI.WILL_RECONNECT,((e,t,i)=>{\"recover\"===e&&i(e),i(\"tryNext\")})),this.workerConnection.on(SI.REQUEST_NEW_URLS,((e,t)=>{this.workerManagerConnection.close(),this.once(mv.REQUEST_NEW_WORKER_URL,(t=>{e([t])})),this.requestAP(this._connectInfo,this._cancelTokenSource.token,this._retryConfig).then((e=>{this.connectWorkerManager(e,!0)})).catch((e=>{t(e)}))}))}static intToLong(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}async requestToInspectImage(){this.sequence++;const e=AT(this,mv.CLIENT_LOCAL_VIDEO_TRACK),t={appId:this._connectInfo.appId,cname:this._connectInfo.cname,cid:this._connectInfo.cid,sid:this._connectInfo.sid,uid:this._connectInfo.uid,vid:this._connectInfo.vid};if(e){if(!e.isPlaying)return void this.emit(mv.INSPECT_RESULT,void 0,new LI(Hg.INVALID_OPERATION,\"Only the track being played can be inspected\"));const i=await this.generateRequestData(e,t);this.workerConnection.sendMessage(i,!0,!0)}else this.emit(mv.INSPECT_RESULT,void 0,new LI(Hg.INVALID_OPERATION,\"Only the track being published can be inspected\"))}async generateRequestData(e,t){let{appId:i,cname:n,cid:r,vid:s,sid:o,uid:a}=t;const c=Date.now(),d=await e.getCurrentFrameImage(\"image/jpeg\",this.quality),l=await gw(d,i,n),u=this.sequence+\"-\"+r+\"-\"+a+\"-\"+c+\"-\"+nS(12,\"\"),h={appId:i,cid:r,cname:n,deviceId:\"\",elapse:FF.intToLong(Number(c-this.inspectStartTime)),fileSize:l.byteLength,jpgEncryption:2,height:d.height,width:d.width,jpg:l,networkType:6,osType:7,requestId:u,sdkVersion:\"4.20.2\",sequence:this.sequence,sid:o,timestamp:FF.intToLong(c),uid:a,vid:s,service:this._inspectMode,callbackData:this.extraInfo,ossFilePrefix:this.ossFilePrefix};void 0===this.extraInfo&&delete h.callbackData,void 0===this.ossFilePrefix&&delete h.ossFilePrefix;const p=lF(h);if(p.byteLength>>3){case 0:break e;case 1:t.code=eB(e);break;case 2:t.msg=XF(e,eB(e));break;case 3:t.requestId=XF(e,eB(e));break;case 4:t.timestamp=iB(e,!1);break;default:GF(e,7&i)}}return t}({bytes:t=e,offset:0,limit:t.length});var t}function GF(e,t){switch(t){case 0:for(;128&ZF(e););break;case 2:KF(e,eB(e));break;case 5:KF(e,4);break;case 1:KF(e,8);break;default:throw new Error(\"Unimplemented type: \"+t)}}function WF(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}let HF=[];function KF(e,t){if(e.offset+t>e.limit)throw new Error(\"Skip past limit\");e.offset+=t}function YF(e){return e.offset>=e.limit}function qF(e,t){let i=e.bytes,n=e.offset,r=e.limit,s=n+t;if(s>i.length){let t=new Uint8Array(2*s);t.set(i),e.bytes=t}return e.offset=s,s>r&&(e.limit=s),n}function zF(e,t){let i=e.offset;if(i+t>e.limit)throw new Error(\"Read past limit\");return e.offset+=t,i}function JF(e,t){let i=qF(e,t.length);e.bytes.set(t,i)}function XF(e,t){let i=zF(e,t),n=String.fromCharCode,r=e.bytes,s=\"\uFFFD\",o=\"\";for(let e=0;e=t?o+=s:(a=r[e+i+1],128!=(192&a)?o+=s:(l=(31&u)<<6|63&a,l<128?o+=s:(o+=n(l),e++))):224==(240&u)?e+2>=t?o+=s:(a=r[e+i+1],c=r[e+i+2],32896!=(49344&(a|c<<8))?o+=s:(l=(15&u)<<12|(63&a)<<6|63&c,l<2048||l>=55296&&l<=57343?o+=s:(o+=n(l),e+=2))):240==(248&u)?e+3>=t?o+=s:(a=r[e+i+1],c=r[e+i+2],d=r[e+i+3],8421504!=(12632256&(a|c<<8|d<<16))?o+=s:(l=(7&u)<<18|(63&a)<<12|(63&c)<<6|63&d,l<65536||l>1114111?o+=s:(l-=65536,o+=n(55296+(l>>10),56320+(1023&l)),e+=3))):o+=s}return o}function QF(e,t){let i=t.length,n=0;for(let e=0;e=55296&&r<=56319&&e+1=55296&&n<=56319&&e+1>6&31|192:(n<65536?s[r++]=n>>12&15|224:(s[r++]=n>>18&7|240,s[r++]=n>>12&63|128),s[r++]=n>>6&63|128),s[r++]=63&n|128)}}function ZF(e){return e.bytes[zF(e,1)]}function $F(e,t){let i=qF(e,1);e.bytes[i]=t}function eB(e){let t,i=0,n=0;do{t=ZF(e),i<32&&(n|=(127&t)<>>=0;t>=128;)$F(e,127&t|128),t>>>=7;$F(e,t)}function iB(e,t){let i,n=0,r=0,s=0;return i=ZF(e),n=127&i,128&i&&(i=ZF(e),n|=(127&i)<<7,128&i&&(i=ZF(e),n|=(127&i)<<14,128&i&&(i=ZF(e),n|=(127&i)<<21,128&i&&(i=ZF(e),r=127&i,128&i&&(i=ZF(e),r|=(127&i)<<7,128&i&&(i=ZF(e),r|=(127&i)<<14,128&i&&(i=ZF(e),r|=(127&i)<<21,128&i&&(i=ZF(e),s=127&i,128&i&&(i=ZF(e),s|=(127&i)<<7))))))))),{low:n|r<<28,high:r>>>4|s<<24,unsigned:t}}function nB(e,t){let i=t.low>>>0,n=(t.low>>>28|t.high<<4)>>>0,r=t.high>>>24,s=0===r?0===n?i<16384?i<128?1:2:i<1<<21?3:4:n<16384?n<128?5:6:n<1<<21?7:8:r<128?9:10,o=qF(e,s),a=e.bytes;switch(s){case 10:a[o+9]=r>>>7&1;case 9:a[o+8]=9!==s?128|r:127&r;case 8:a[o+7]=8!==s?n>>>21|128:n>>>21&127;case 7:a[o+6]=7!==s?n>>>14|128:n>>>14&127;case 6:a[o+5]=6!==s?n>>>7|128:n>>>7&127;case 5:a[o+4]=5!==s?128|n:127&n;case 4:a[o+3]=4!==s?i>>>21|128:i>>>21&127;case 3:a[o+2]=3!==s?i>>>14|128:i>>>14&127;case 2:a[o+1]=2!==s?i>>>7|128:i>>>7&127;case 1:a[o]=1!==s?128|i:127&i}}const rB={},sB={},oB=4294967296,aB=oB*oB,cB=aB/2,dB=_B(0,!0),lB=_B(0),uB=EB(0,-2147483648,!1),hB=EB(-1,2147483647,!1),pB=EB(-1,-1,!0);function _B(e,t){let i,n,r;return t?(r=0<=(e>>>=0)&&e<256)&&(n=sB[e],n)?n:(i=EB(e,0,!0),r&&(sB[e]=i),i):(r=-128<=(e|=0)&&e<128)&&(n=rB[e],n)?n:(i=EB(e,e<0?-1:0,!1),r&&(rB[e]=i),i)}function EB(e,t,i){return{low:0|e,high:0|t,unsigned:!!i}}function mB(e,t){if(isNaN(e))return t?dB:lB;if(t){if(e<0)return dB;if(e>=aB)return pB}else{if(e<=-cB)return uB;if(e+1>=cB)return hB}return e<0?t?dB:lB:EB(e%oB|0,e/oB|0,t)}function fB(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}class gB extends dT{get connectionState(){return this._connectionState}set connectionState(e){if(this._connectionState===e)return;const t=this._connectionState;this._connectionState=e,this.emit(Cv.CONNECTION_STATE_CHANGE,e,t)}get quality(){return this._quality}set quality(e){this._quality=e>1?1:e<.1?.1:e,this._qualityTimer&&(window.clearTimeout(this._qualityTimer),this._qualityTimer=null),this._quality>=1||(this._qualityTimer=window.setTimeout((()=>{this.quality=this._quality/this._qualityRatio}),6e4))}constructor(e){var t;super(),sh(this,\"name\",\"AgoraRTCImageModeration\"),sh(this,\"_connectionState\",Rv.CONNECTING),sh(this,\"_sequence\",0),sh(this,\"_moderationStartTime\",void 0),sh(this,\"_workerConnection\",void 0),sh(this,\"_workerMessageLengthLimit\",void 0),sh(this,\"_qualityRatio\",void 0),sh(this,\"_connectInfo\",void 0),sh(this,\"_cancelTokenSource\",sC.CancelToken.source()),sh(this,\"_retryConfig\",void 0),sh(this,\"_moderationInterval\",void 0),sh(this,\"_moderationTimer\",null),sh(this,\"_moderationMode\",1),sh(this,\"_quality\",1),sh(this,\"_qualityTimer\",null),sh(this,\"_ticket\",void 0),sh(this,\"_moderationIntervalMinimum\",void 0),sh(this,\"_uploadFailedNum\",0),sh(this,\"_uploadNum\",0),sh(this,\"_uploadTimer\",null),sh(this,\"_extraInfo\",void 0),sh(this,\"_vendor\",\"\"),sh(this,\"_encoder\",new TextEncoder),sh(this,\"_moderationId\",void 0),sh(this,\"inspectImage\",(()=>{if(this.connectionState!==Rv.CONNECTED)throw new LI(Hg.OPERATION_ABORTED,\"image moderation service connection status is \".concat(this.connectionState));this._moderationTimer&&(window.clearInterval(this._moderationTimer),this._moderationTimer=null),this._moderationTimer=window.setInterval((()=>{this.connectionState===Rv.CONNECTED?this.requestToInspectImage():jC.debug(\"[\".concat(this._moderationId,\"] Moderation State is not connected , \"),this.connectionState)}),this._moderationInterval{jC.debug(\"[\".concat(this._moderationId,\"] Moderation operation :\").concat(Iv[e],\" \").concat(t||\"\"))})),this.handleWorkerEvents()}async init(e,t){this.emit(Cv.STATE_CHANGE,Iv.CONNECT_AP),this._connectInfo=e;const i=this._cancelTokenSource.token;return this._retryConfig=t,new cg(((n,r)=>{this.on(Cv.CONNECTION_STATE_CHANGE,((e,t)=>{e===Rv.CONNECTED&&n()})),this.requestAP(e,i,t).then((e=>{this.connectWorker(e)})).catch((e=>{r(e)}))}))}updateConfig(e){var t;this._moderationInterval=null!==(t=e.interval)&&void 0!==t?t:1e3,e.extraInfo&&(this._extraInfo=this._encoder.encode(e.extraInfo)),e.vendor&&(this._vendor=e.vendor),jC.debug(\"[\".concat(this._moderationId,\"] updateConfig: \").concat(JSON.stringify(e))),this.connectionState===Rv.CONNECTED&&this.inspectImage()}async requestAP(e,t,i){const n=RC(\"WEBCS_DOMAIN\").map((e=>\"https://\".concat(e,\"/api/v1\"))),r=await function(e,t,i,n){let{appId:r,areaCode:s,cname:o,sid:a,token:c,uid:d}=t;cA++;const l=\"moderation_plugin\",u={service_name:l,json_body:JSON.stringify({appId:r,areaCode:s,cname:o,command:\"allocateEdge\",requestId:cA,seq:cA,sid:a,appToken:c,ts:Date.now(),uid:d+\"\"})};let h,p,_=e[0];return fS((async()=>{h=Date.now();const e=await By(_,{data:u,cancelToken:i,headers:{\"X-Packet-Service-Type\":\"0\",\"X-Packet-URI\":\"61\"},params:{action:\"wrtc_gateway\"}});if(p=Date.now()-h,0!==e.code){const t=new LI(Hg.UNEXPECTED_RESPONSE,\"moderation plugin ap error, code\"+e.code,{retry:!0,responseTime:p});throw jC.error(t.toString()),t}const t=JSON.parse(e.json_body);if(200!==t.code){const e=new LI(Hg.UNEXPECTED_RESPONSE,\"moderation plugin ap error, code: \".concat(t.code,\", reason: \").concat(t.reason),{code:t.code,responseTime:p});throw jC.error(e.toString()),e}if(!t.servers||!Array.isArray(t.servers)||0===t.servers.length){const e=new LI(Hg.UNEXPECTED_RESPONSE,\"moderation plugin ap empty server\",{code:t.code,responseTime:p});throw jC.error(e.toString()),e}if(!t.servers.some((e=>!!e.wss))){const e=new LI(Hg.UNEXPECTED_RESPONSE,\"moderation plugin ap empty port\",{code:t.code,responseTime:p});throw jC.error(e.toString()),e}const n=RC(\"IMAGE_MODERATION_WORKER_HOST\");return{addressList:t.servers.map((e=>{let{address:t,wss:i}=e;if(t&&i)return\"wss://\".concat(t.replace(/\\./g,\"-\"),\".\").concat(n,\":\").concat(i,\"/moderation\")})).filter((e=>!!e)),workerToken:t.workerToken,vid:t.vid,ticket:t.appTicket,responseTime:p}}),((t,i)=>(eI.apworkerEvent(a,{success:!0,sc:200,serviceName:l,responseDetail:JSON.stringify(t.addressList),firstSuccess:0===i,responseTime:p,serverIp:e[i%e.length]}),!1)),((t,i)=>(eI.apworkerEvent(a,{success:!1,sc:t.data&&t.data.code||200,serviceName:l,responseTime:p,serverIp:e[i%e.length]}),!!(t.code!==Hg.OPERATION_ABORTED&&t.code!==Hg.UNEXPECTED_RESPONSE||t.data&&t.data.retry)&&(_=e[(i+1)%e.length],!0))),n)}(n,e,t,i);this.emit(Cv.STATE_CHANGE,Iv.AP_CONNECTED);const{addressList:s,ticket:o}=r;return this._ticket=o,s}async connectWorker(e){this.emit(Cv.STATE_CHANGE,Iv.CONNECT_WORKER),await this._workerConnection.init(e,1e4)}handleWorkerEvents(){this._workerConnection.on(SI.CONNECTED,(async()=>{this.emit(Cv.STATE_CHANGE,Iv.WORKER_CONNECTED,this._workerConnection.url),this.connectionState=Rv.CONNECTED})),this._workerConnection.on(SI.CLOSED,(()=>{this.connectionState=Rv.CLOSED})),this._workerConnection.on(SI.FAILED,(()=>{this.connectionState=Rv.CLOSED})),this._workerConnection.on(SI.RECONNECTING,(()=>{this.connectionState=this.connectionState===Rv.CONNECTED?Rv.RECONNECTING:Rv.CONNECTING})),this._workerConnection.on(SI.ON_MESSAGE,(async e=>{if(e.data instanceof ArrayBuffer){const t=jF(new Uint8Array(e.data));RC(\"SHOW_IMAGE_MODERATION_WORKER_MESSAGE\")&&jC.debug(\"[\".concat(this._moderationId,\"] Response message for worker of image moderation \"),JSON.stringify(t)),this._uploadNum++,void 0===t.code||0===t.code||(this._uploadFailedNum++,jC.error(\"[\".concat(this._moderationId,\"] Error response from worke, code is \").concat(t.code,\", msg is \").concat(t.msg)),this._uploadTimer||(this._uploadTimer=window.setTimeout((()=>{eI.reportApiInvoke(this._connectInfo.sid||null,{name:hT.IMAGE_MODERATION_UPLOAD,options:[this._uploadFailedNum,this._uploadNum,t.code],tag:pT.TRACER}).onError(new LI(Hg.IMAGE_MODERATION_UPLOAD_FAILED,t.msg)),this._uploadTimer=null}),RC(\"IMAGE_MODERATION_UPLOAD_REPORT_INTERVAL\"))))}else jC.error(\"[\".concat(this._moderationId,\"] Unexpected message type from worker\"))})),this._workerConnection.on(SI.WILL_RECONNECT,((e,t,i)=>{\"recover\"===e&&i(e),i(\"tryNext\")})),this._workerConnection.on(SI.REQUEST_NEW_URLS,((e,t)=>{this.requestAP(this._connectInfo,this._cancelTokenSource.token,this._retryConfig).then(e).catch(t)}))}static intToLong(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}async requestToInspectImage(){const e=AT(this,Cv.CLIENT_LOCAL_VIDEO_TRACK),t={appId:this._connectInfo.appId,cname:this._connectInfo.cname,cid:this._connectInfo.cid,sid:this._connectInfo.sid,uid:this._connectInfo.uid,vid:this._connectInfo.vid};if(e){if(!e.isPlaying)return void(RC(\"SHOW_IMAGE_MODERATION_WORKER_MESSAGE\")&&jC.debug(\"Only the track being played can be inspected\"));this._sequence++;const i=await this.generateRequestData(e,t);this._workerConnection.sendMessage(i,!0,!0)}else RC(\"SHOW_IMAGE_MODERATION_WORKER_MESSAGE\")&&jC.debug(\"Only the track being published can be inspected\")}async generateRequestData(e,t){let{appId:i,cname:n,cid:r,vid:s,sid:o,uid:a}=t;const c=Date.now(),d=await e.getCurrentFrameImage(\"image/jpeg\",this.quality),l=await gw(d,i,n),u=this._sequence+\"-\"+r+\"-\"+a+\"-\"+c+\"-\"+nS(12,\"\"),h={appId:i,cid:r,cname:n,deviceId:\"\",elapse:gB.intToLong(Number(c-this._moderationStartTime)),fileSize:d.buffer.byteLength,height:d.height,width:d.width,jpg:l,networkType:6,osType:7,requestId:u,sdkVersion:\"4.20.2\",sequence:this._sequence,sid:o,timestamp:mB(c),uid:a,vid:s,service:this._moderationMode,ticket:this._ticket,callbackData:this._extraInfo,vendorConfigs:this._vendor};void 0===this._extraInfo&&delete h.callbackData;const p=BF(h);if(p.byteLength0&&(n.firstRecvTs=Date.now()-s);let a=i.mediaDelay+o;a<=0?(t.pop(),AB(i.context,r),a=0):a=Math.min(a,CB),setTimeout((()=>t.length&&yB(e)),a)}function AB(e,t){e.safeEmit(mT.STREAM_MESSAGE,t.uid,t.payload),e.onStreamMessage&&e.onStreamMessage(t)}function bB(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2?arguments[2]:void 0;if(!e.syncWithAudio)return AB(i,{uid:e.uid,payload:e.payload});const n=\"\".concat(i.id,\"-\").concat(e.uid),r=IB.get(n)||[],s=r.findIndex((t=>e.sendTs>=t.sendTs)),o=SB(SB({},e),{},{context:i,mediaDelay:t,recvTs:Date.now()});-1===s?r.push(o):r.splice(s,0,o),IB.set(n,r);let a=!1;var c;vB.has(n)?a=!(null===(c=vB.get(n))||void 0===c||!c.isSyncing):vB.set(n,{isSyncing:a,firstRecvTs:0,firstSendTs:0});a||yB(n)}const wB=Sg().name;function OB(){return!function(e,t,i){const n=Sg();if(n.os!==_g.IOS||!n.osVersion)return!1;const r=n.osVersion.split(\".\");return i?t&&Number(r[0])===e&&Number(r[1]){this.publish(e,!1).then(t).catch(i)})),sh(this,\"_handleLocalTrackDisable\",((e,t,i)=>{this.unpublish(e).then(t).catch(i)})),sh(this,\"_handleUserOnline\",(e=>{if(RC(\"BLOCK_LOCAL_CLIENT\")&&sI(e.uid,this.channelName))return void jC.debug(\"[\".concat(e.uid,\"] will be ignored in local\"));this.isStringUID&&\"string\"!=typeof e.uid&&jC.error(\"[\".concat(this._clientId,\"] StringUID is Mixed with UintUID\"));const t=this._users.find((t=>t.uid===e.uid));if(t)t._trust_in_room_=!0,t._is_pre_created&&(t._is_pre_created=!1,this.safeEmit(mT.USER_JOINED,t));else{const t=new sV(e.uid,e.uint_id||e.uid);this._users.push(t),jC.debug(\"[\".concat(this._clientId,\"] user online\"),e.uid),this.safeEmit(mT.USER_JOINED,t)}})),sh(this,\"_handleUserOffline\",(e=>{if(RC(\"BLOCK_LOCAL_CLIENT\")&&sI(e.uid,this.channelName))return;const t=this._users.find((t=>t.uid===e.uid));t&&(this._handleRemoveStream(e),this._handleRemoveDataChannels(e),t._audio_pre_subscribed||t._video_pre_subscribed?t._is_pre_created=!0:WT(this._users,t),this._remoteStreamTypeCacheMap.delete(t.uid),this._streamFallbackTypeCacheMap.delete(t.uid),jC.debug(\"[\".concat(this._clientId,\"] user offline\"),e.uid,\"reason:\",e.reason),this.safeEmit(mT.USER_LEAVED,t,e.reason))})),sh(this,\"_handleAddAudioOrVideoStream\",((e,t,i,n,r,s,o)=>{if(RC(\"BLOCK_LOCAL_CLIENT\")&&sI(t,this.channelName))return;const a=this._users.find((e=>e.uid===t));if(!a)return void jC.error(\"[\".concat(this._clientId,\"] can not find target user!(on_add_stream)\"));jC.debug(\"[\".concat(this._clientId,\"] stream added with uid \").concat(t,\", type \").concat(e)),this.store.subscribe(a.uid,e,void 0,void 0,void 0,Date.now());const c=\"audio\"===e?a.hasAudio:a.hasVideo;a._uintid||(a._uintid=r||t),\"audio\"===e?a._trust_audio_stream_added_state_=!0:a._trust_video_stream_added_state_=!0,\"audio\"===e?(a._audio_added_=!0,void 0!==i&&(a._audioSSRC=i),void 0!==n&&(a._cname=n),s&&(a._audioOrtc=s)):(a._video_added_=!0,void 0!==i&&(a._videoSSRC=i),void 0!==n&&(a._cname=n),void 0!==o&&(a._rtxSsrcId=o),s&&(a._videoOrtc=s)),(\"audio\"===e?a.hasAudio:a.hasVideo)&&!c&&(jC.info(\"[\".concat(this._clientId,\"] remote user \").concat(a.uid,\" published \").concat(e)),this.safeEmit(mT.USER_PUBLISHED,a,e)),\"video\"===e?eI.onGatewayStream(this._sessionId,YC.ON_ADD_VIDEO_STREAM,qC.ON_ADD_VIDEO_STREAM,{peer:r||t,ssrc:a._videoSSRC}):eI.onGatewayStream(this._sessionId,YC.ON_ADD_AUDIO_STREAM,qC.ON_ADD_AUDIO_STREAM,{peer:r||t,ssrc:a._audioSSRC}),this._p2pChannel.remoteMediaSsrcChanged(a,e,i).then((t=>{if(t&&(jC.debug(\"[\".concat(this._clientId,\"] resubscribe \").concat(e,\" for user \").concat(a.uid,\" after rejoin because SSRC id changed.\")),this._p2pChannel instanceof cF))return this._p2pChannel.unsubscribe(a,e,!0).then((()=>this._subscribe(a,e,!0).catch((e=>{jC.error(\"[\".concat(this._clientId,\"] resubscribe error\"),e.toString())}))))})),this._p2pChannel.hasPendingRemoteMedia(a,e)&&(jC.debug(\"[\".concat(this._clientId,\"] resubscribe \").concat(e,\" for user \").concat(a.uid,\" after reconnect.\")),this._subscribe(a,e,!0).catch((e=>{jC.error(\"[\".concat(this._clientId,\"] resubscribe error\"),e.toString())})))})),sh(this,\"_handleRemoveStream\",(e=>{if(RC(\"BLOCK_LOCAL_CLIENT\")&&sI(e.uid,this.channelName))return;const t=this._users.find((t=>t.uid===e.uid));if(!t)return void jC.warning(\"[\".concat(this._clientId,\"] can not find target user!(on_remove_stream)\"));jC.debug(\"[\".concat(this._clientId,\"] stream removed with uid \").concat(e.uid));let i=()=>{};t.hasAudio&&t.hasVideo?i=()=>{jC.info(\"[\".concat(this._clientId,\"] remote user \").concat(t.uid,\" unpublished audio track\")),this.safeEmit(mT.USER_UNPUBLISHED,t,\"audio\"),jC.info(\"[\".concat(this._clientId,\"] remote user \").concat(t.uid,\" unpublished video track\")),this.safeEmit(mT.USER_UNPUBLISHED,t,\"video\")}:t.hasVideo?i=()=>{jC.info(\"[\".concat(this._clientId,\"] remote user \").concat(t.uid,\" unpublished video track\")),this.safeEmit(mT.USER_UNPUBLISHED,t,\"video\")}:t.hasAudio&&(i=()=>{jC.info(\"[\".concat(this._clientId,\"] remote user \").concat(t.uid,\" unpublished audio track\")),this.safeEmit(mT.USER_UNPUBLISHED,t,\"audio\")}),t._video_pre_subscribed||t._audio_pre_subscribed||(t._trust_audio_stream_added_state_=!0,t._trust_video_stream_added_state_=!0,t._audio_added_=!1,t._video_added_=!1,this._p2pChannel instanceof cF&&this._p2pChannel.unsubscribe(t).then((e=>{if(e)return this._gateway.unsubscribe(e,t.uid)})),t._audioSSRC=void 0,t._videoSSRC=void 0,t._audioOrtc=void 0,t._videoOrtc=void 0,t._rtxSsrcId=void 0),eI.onGatewayStream(this._sessionId,YC.ON_REMOVE_STREAM,qC.ON_REMOVE_STREAM,{peer:e.uint_id||e.uid}),i()})),sh(this,\"_handleSetStreamLocalEnable\",((e,t,i)=>{if(RC(\"BLOCK_LOCAL_CLIENT\")&&sI(t,this.channelName))return;const n=this._users.find((e=>e.uid===t));if(!n)return void jC.error(\"[\".concat(this._clientId,\"] can not find target user!(disable_local)\"));jC.debug(\"[\".concat(this._clientId,\"] local \").concat(e,\" \").concat(i?\"enabled\":\"disabled\",\" with uid \").concat(t));const r=\"audio\"===e?n.hasAudio:n.hasVideo;if(\"audio\"===e){n._trust_audio_enabled_state_=!0;const e=n._audio_enabled_;if(n._audio_enabled_=i,n._audio_enabled_===e)return;{const e=n._audio_enabled_?\"enable-local-audio\":\"disable-local-audio\";jC.debug(\"[\".concat(this._clientId,\"] user-info-updated, uid: \").concat(t,\", msg: \").concat(e)),this.safeEmit(mT.USER_INFO_UPDATED,t,e)}}else{n._trust_video_enabled_state_=!0;const e=n._video_enabled_;if(n._video_enabled_=i,n._video_enabled_===e)return;{const e=n._video_enabled_?\"enable-local-video\":\"disable-local-video\";jC.debug(\"[\".concat(this._clientId,\"] user-info-update, uid: \").concat(t,\", msg: \").concat(e)),this.safeEmit(mT.USER_INFO_UPDATED,t,e)}}const s=\"audio\"===e?n.hasAudio:n.hasVideo;return r!==s?!r&&s?(jC.info(\"[\".concat(this._clientId,\"] remote user \").concat(t,\" published \").concat(e)),void this.safeEmit(mT.USER_PUBLISHED,n,e)):(\"video\"===e&&n._videoTrack&&n._videoTrack._destroy(),\"audio\"===e&&n._audioTrack,this._p2pChannel.muteRemote(n,e),jC.info(\"[\".concat(this._clientId,\"] remote user \").concat(t,\" unpublished \").concat(e)),void this.safeEmit(mT.USER_UNPUBLISHED,n,e)):void 0})),sh(this,\"_handleMuteStream\",((e,t,i)=>{if(RC(\"BLOCK_LOCAL_CLIENT\")&&sI(e,this.channelName))return;jC.debug(\"[\".concat(this._clientId,\"] receive mute message\"),e,t,i);const n=this._users.find((t=>t.uid===e));if(!n)return void jC.warning(\"[\".concat(this._clientId,\"] can not find remote user, ignore mute event, uid: \").concat(e));const r=\"audio\"===t?n.hasAudio:n.hasVideo;if(\"audio\"===t){n._trust_audio_mute_state_=!0;const t=n._audio_muted_;if(n._audio_muted_=i,n._audio_muted_===t)return;{const t=n._audio_muted_?\"mute-audio\":\"unmute-audio\";jC.debug(\"[\".concat(this._clientId,\"] user-info-update, uid: \").concat(e,\", msg: \").concat(t)),this.safeEmit(mT.USER_INFO_UPDATED,e,t)}}else{n._trust_video_mute_state_=!0;const t=n._video_muted_;if(n._video_muted_=i,n._video_muted_===t)return;{const t=n._video_muted_?\"mute-video\":\"unmute-video\";jC.debug(\"[\".concat(this._clientId,\"] user-info-update, uid: \").concat(e,\", msg: \").concat(t)),this.safeEmit(mT.USER_INFO_UPDATED,e,t)}}const s=\"audio\"===t?n.hasAudio:n.hasVideo;if(r!==s){if(!r&&s){return(\"audio\"===t?n._audioSSRC:n._videoSSRC)?(jC.info(\"[\".concat(this._clientId,\"] remote user \").concat(e,\" published \").concat(t)),void this.safeEmit(mT.USER_PUBLISHED,n,t)):void jC.warning(\"[\".concat(this._clientId,\"] remote user \").concat(e,\" receive \").concat(t,\" unmute message before add stream message, \").concat(t,\" SSRC doesn't exist yet.\"))}\"video\"===t&&n._videoTrack&&!n._video_pre_subscribed&&n._videoTrack._destroy(),\"audio\"===t&&n._audioTrack,this._p2pChannel.muteRemote(n,t),jC.info(\"[\".concat(this._clientId,\"] remote user \").concat(e,\" unpublished \").concat(t)),this.safeEmit(mT.USER_UNPUBLISHED,n,t)}})),sh(this,\"_handleP2PLost\",(async e=>{jC.debug(\"[\".concat(this._clientId,\"] receive p2p lost\"),e),parseInt(e.p2pid,10)===this.store.p2pId?await this._p2pChannel.requestReconnect():jC.warning(\"[\".concat(this._clientId,\"] P2PLost stream not found\"),e)})),sh(this,\"_handleTokenWillExpire\",(()=>{jC.debug(\"[\".concat(this._clientId,\"] received message onTokenPrivilegeWillExpire\")),this.safeEmit(mT.ON_TOKEN_PRIVILEGE_WILL_EXPIRE)})),sh(this,\"_handleBeforeUnload\",(e=>{\"beforeunload\"===e.type&&void 0!==e.returnValue&&\"\"!==e.returnValue||(this.leave(),jC.info(\"[\".concat(this._clientId,\"] auto leave onbeforeunload or pagehide\")))})),sh(this,\"_handleUpdateNetworkQuality\",(()=>{if(\"normal\"===this._networkQualitySensitivity)return;if(navigator&&void 0!==navigator.onLine&&!navigator.onLine)return void this.safeEmit(mT.NETWORK_QUALITY,{downlinkNetworkQuality:6,uplinkNetworkQuality:6});const e={downlinkNetworkQuality:0,uplinkNetworkQuality:0};e.uplinkNetworkQuality=this._p2pChannel.getUplinkNetworkQuality(),e.downlinkNetworkQuality=this._p2pChannel.getDownlinkNetworkQuality(),this.safeEmit(mT.NETWORK_QUALITY,e)})),sh(this,\"_handleP2PAddAudioOrVideoStream\",((e,t,i,n)=>{const r=this._users.find((e=>e.uid===t));if(!r)return void jC.error(\"[\".concat(this._clientId,\"] can not find target user!(on_add_stream)\"));jC.debug(\"[\".concat(this._clientId,\"] stream added with uid \").concat(t,\", type \").concat(e)),this.store.subscribe(r.uid,e,void 0,void 0,void 0,Date.now());const s=\"audio\"===e?r.hasAudio:r.hasVideo;\"audio\"===e?r._trust_audio_stream_added_state_=!0:r._trust_video_stream_added_state_=!0,\"audio\"===e?(r._audio_added_=!0,void 0!==i&&(r._audioSSRC=i),void 0!==n&&(r._audioMid=n)):(r._video_added_=!0,void 0!==i&&(r._videoSSRC=i),void 0!==n&&(r._videoMid=n)),(\"audio\"===e?r.hasAudio:r.hasVideo)&&!s&&(jC.info(\"[\".concat(this._clientId,\"] remote user \").concat(r.uid,\" published \").concat(e)),this.safeEmit(mT.USER_PUBLISHED,r,e)),this._p2pChannel.hasPendingRemoteMedia(r,e)&&(jC.debug(\"[\".concat(this._clientId,\"] resubscribe \").concat(e,\" for user \").concat(r.uid,\" after reconnect.\")),this._subscribe(r,e,!0).catch((e=>{jC.error(\"[\".concat(this._clientId,\"] resubscribe error\"),e.toString())})))})),this._config=e,this._clientId=nS(5,\"client-\"),this.store=new AC(e.codec,e.audioCodec,e.mode,this._clientId),this.store.clientCreated(),e.proxyServer&&this.setProxyServer(e.proxyServer,!0),e.turnServer&&this.setTurnServer(e.turnServer,!0),jC.info(\"[\".concat(this._clientId,\"] Initializing AgoraRTC client v\").concat(EC,\" build: \").concat(gC,\", mode: \").concat(this.mode,\", codec: \").concat(this.codec)),e.clientRoleOptions)try{IT(e.clientRoleOptions),t=Object.assign({},e.clientRoleOptions)}catch(e){jC.warning(\"[\".concat(this._clientId,\"] \").concat(e.toString()))}this._statsCollector=new mV(this.store),this._statsCollector.onStatsException=(e,t,i)=>{jC.debug(\"[\".concat(this._clientId,\"] receive exception msg, code: \").concat(e,\", msg: \").concat(t,\", uid: \").concat(i)),this.safeEmit(mT.EXCEPTION,{code:e,msg:t,uid:i})},this._statsCollector.onUploadPublishDuration=(e,t,i,n)=>{const r=this._users.find((t=>t.uid===e));r&&eI.peerPublishStatus(this._sessionId,{subscribeElapse:n,audioPublishDuration:t,videoPublishDuration:i,peer:r._uintid})},this.store.useDataChannel=IA().supportDataChannel&&RC(\"SIGNAL_CHANNEL\"),this.store.useP2P=\"p2p\"===e.mode,this._gateway=new xy(this.store,{clientId:this._clientId,mode:this.mode,codec:this.codec,websocketRetryConfig:e.websocketRetryConfig||ES,httpRetryConfig:e.httpRetryConfig||ES,forceWaitGatewayResponse:void 0===e.forceWaitGatewayResponse||e.forceWaitGatewayResponse,statsCollector:this._statsCollector,role:e.role,clientRoleOptions:t}),this._configDistribute=new RA,this.store.useP2P?(this._p2pChannel=new hV(this.store,this._statsCollector),this._handleP2PEvents()):this._p2pChannel=new cF(this.store,this._statsCollector),this._handleP2PChannelEvents(),this._handleGatewayEvents(),this._handleGatewaySignalEvents()}async joinMeta(e,t,i,n,r){let s=!(arguments.length>5&&void 0!==arguments[5])||arguments[5],o=arguments.length>6&&void 0!==arguments[6]&&arguments[6];SC(\"JOIN_GATEWAY_USE_443PORT_ONLY\",s),SC(\"JOIN_GATEWAY_USE_DUAL_DOMAIN\",o);const a=this._gateway.signal.websocket;return a instanceof qv&&(a.use443PortOnly=s,a.tryDoubleDomain=o),async function(e,t,i){ug.get(e)||ug.set(e,[]),hg.get(e)||hg.set(e,t),pg.get(e)||pg.set(e,0);const n=ug.get(e),r=hg.get(e);if(!n||!r)throw new Error(\"concurrent: deferQueue or maxConcurrency is null\");if(pg.get(e)===r){const e=lg();n.push(e),await e.promise}pg.set(e,pg.get(e)+1);for(var s=arguments.length,o=new Array(s>3?s-3:0),a=3;a0&&(n[0].resolve(),n.shift()),0===pg.get(e)&&(ug.set(e,[]),hg.set(e,0),pg.set(e,0)),c}(\"client.join\",RC(\"JOIN_MAX_CONCURRENCY\"),this.join.bind(this),e,t,i,n,r)}async join(e,t,i,n,r){const s=++this._numberOfJoinCount;this.store.joinStart(),n&&(this.store.uid=n);const o=pC(),a=_C()?window.isSecureContext:\"Browser Not Support\";if(!_C()&&!o||!window.isSecureContext){const e=\"The website must be running in a secure context (About secure context: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts ), otherwise the media collection will be restricted by the browser\";jC.warning(e)}const c=rS();\"DISCONNECTED\"===this.connectionState&&(this.store.avoidJoinStart=Math.round(Date.now()),jC.debug(\"[\".concat(this._clientId,\"] set avoidJoinStart to \").concat(this.store.avoidJoinStart)));const d=eI.reportApiInvoke(c,{name:hT.JOIN,options:[e,t,i,n],states:{isHttps:o,isSecureContext:a},tag:pT.TRACER});eI.setAppId(e);try{if(!i&&null!==i)throw new LI(Hg.INVALID_PARAMS,\"Invalid token: \".concat(i,\". If you don not use token, set it to null\"));i&&Xg(i,\"token\",1,2047),Xg(e,\"appid\",1,2047),kI(t),n&&MI(n),r&&Xg(r,\"optionalInfo\",1,2047)}catch(e){throw d.onError(e),e}if(jC.info(\"[\".concat(this._clientId,\"] start join channel \").concat(t,\", join number: \").concat(s)),this._leaveMutex.isLocked){jC.debug(\"[\".concat(this._clientId,\"] join: waiting leave operation\"));(await this._leaveMutex.lock())(),jC.debug(\"[\".concat(this._clientId,\"] join: continue\"))}if(this._joinAndNotLeaveYet=!0,\"DISCONNECTED\"!==this.connectionState){const e=new LI(Hg.INVALID_OPERATION,\"[\".concat(this._clientId,\"] Client already in connecting/connected state\"));throw d.onError(e),e}this._sessionId||(this._sessionId=c,this.store.sessionId=this._sessionId),this._gateway.state=\"CONNECTING\";const l=DB(DB({},this._rtmConfig),{},{clientId:this._clientId,appId:e,sid:this._sessionId,cname:t,uid:\"string\"!=typeof n?n:null,turnServer:this._turnServer,proxyServer:this._proxyServer,token:i||e,cloudProxyServer:this._cloudProxyServerMode,optionalInfo:r,license:this._license,useLocalAccessPoint:this._useLocalAccessPoint},void 0!==this._remoteDefaultVideoStreamType&&{defaultVideoStream:this._remoteDefaultVideoStreamType});if(this._useLocalAccessPoint&&(l.setLocalAPVersion=this._setLocalAPVersion),\"string\"==typeof n&&(l.stringUid=n,this._uintUid?(l.uid=this._uintUid,this._uintUid=void 0):l.uid=0),\"none\"!==this._encryptionMode&&this._encryptionSecret){if(l.aesmode=this._encryptionMode,l.aespassword=await aT(this._encryptionSecret),!this._joinAndNotLeaveYet)throw new LI(Hg.INVALID_OPERATION,\"[\".concat(this._clientId,\"] Client already left\"));this._encryptionSalt&&(l.aessalt=this._encryptionSalt)}if(this._encryptDataStream&&(\"aes-128-gcm2\"===this._encryptionMode||\"aes-256-gcm2\"===this._encryptionMode))if(this._encryptionSalt&&this._encryptionSecret)if(window.crypto.subtle){const e=new TextEncoder,t=RC(\"USE_PURE_ENCRYPTION_MASTER_KEY\")?e.encode(l.appId+this._encryptionSecret+this._encryptionSecret):e.encode(l.appId+l.cname+this._encryptionSecret);this._encryptDataStreamIv=await async function(e,t,i){const n=await window.crypto.subtle.importKey(\"raw\",t,\"PBKDF2\",!1,[\"deriveBits\",\"deriveKey\"]),r=\"aes-128-gcm2\"===e?128:256,s=await window.crypto.subtle.deriveBits({name:\"PBKDF2\",iterations:DC,hash:\"SHA-256\",salt:i},n,r+NC);return new Uint8Array(s).subarray(r/8)}(this._encryptionMode,t,XT(this._encryptionSalt)),this._encryptDataStreamKey=await async function(e,t,i){const n=await window.crypto.subtle.importKey(\"raw\",t,\"PBKDF2\",!1,[\"deriveBits\",\"deriveKey\"]),r=\"aes-128-gcm2\"===e?128:256;return await window.crypto.subtle.deriveKey({name:\"PBKDF2\",iterations:DC,hash:\"SHA-256\",salt:i},n,{name:\"AES-GCM\",length:r},!0,[\"encrypt\",\"decrypt\"])}(this._encryptionMode,t,XT(this._encryptionSalt))}else a?jC.warning(\"[\".concat(this._clientId,\"] encrypt datastream must be running in a secure context, fallback to plain data stream\")):jC.warning(\"[\".concat(this._clientId,\"] current browser do not support WebCrypto ,fallback to plain data stream\")),this._encryptDataStream=!1;else this._encryptDataStream=!1,jC.debug(\"[\".concat(this._clientId,\"] no salt / secret, cannot support encrypt data stream, fallback to plain data stream\"));this._startSession(this._sessionId,{channel:t,appId:e,stringUid:l.stringUid});const u=this._sessionId;setTimeout((()=>{\"CONNECTING\"===this.connectionState&&u===this._sessionId&&eI.joinChannelTimeout(this._sessionId,5)}),5e3);try{var h;let n;const r=l.cloudProxyServer;if(bn(h=[\"proxy3\",\"proxy4\",\"proxy5\"]).call(h,r)){const e=RC(\"PROXY_SERVER_TYPE3\");Array.isArray(e)?l.proxyServer=e[0]:l.proxyServer=e}if(eI.setProxyServer(l.proxyServer),jC.setProxyServer(l.proxyServer),this.store.requestAPStart(),l.stringUid&&!l.uid){let e;[e,n]=await cg.all([pA(l.stringUid,l,this._axiosCancelSource.token,this._config.httpRetryConfig||ES,this.store),hA(l,this._axiosCancelSource.token,this._config.httpRetryConfig||ES,!0,this.store)]),jC.debug(\"[\".concat(this._clientId,\"] getUserAccount Success \").concat(l.stringUid,\" => \").concat(e)),l.uid=e,n.gatewayInfo.uid=e,n.gatewayInfo.res.uid=e}else n=await hA(l,this._axiosCancelSource.token,this._config.httpRetryConfig||ES,!0,this.store);if(!this._joinAndNotLeaveYet)throw new LI(Hg.INVALID_OPERATION,\"[\".concat(this._clientId,\"] Client already left\"));this.store.requestAPEnd(),setTimeout((()=>{this._configDistribute.startGetConfigDistribute(l,this._axiosCancelSource.token),this._configDistribute.on(sv.UPDATE_BITRATE_LIMIT,(e=>{this._p2pChannel.updateBitrateLimit(e)}))}),0),this._key=i||e;const s=n.gatewayInfo,o=l.uid?l.uid:s.uid;this._joinInfo=DB(DB({},l),{},{cid:s.cid,uid:o,vid:s.vid,apResponse:s.res,uni_lbs_ip:s.uni_lbs_ip,gatewayAddrs:s.gatewayAddrs}),this.store.intUid=o;const a=await this._joinGateway();if(!this._joinAndNotLeaveYet)throw new LI(Hg.INVALID_OPERATION,\"[\".concat(this._clientId,\"] Client already left\"));d.onSuccess(a),this._appId=e,this._channelName=l.cname,this._uid=a,this.store.uid=a,setTimeout((()=>{this._networkQualityInterval&&window.clearInterval(this._networkQualityInterval),this._networkQualityInterval=window.setInterval(this._handleUpdateNetworkQuality,2e3),window.addEventListener(bg()?\"beforeunload\":\"pagehide\",this._handleBeforeUnload)}),0);const c=l.stringUid?\"string uid: \".concat(l.stringUid,\",uid: \").concat(l.uid):\"uid: \".concat(this._uid);return jC.info(\"[\".concat(this._clientId,\"] Joining channel success: channel: \").concat(t,\",\").concat(c)),setTimeout((()=>{jC.startUpload()}),5e3),this.store.joinEnd(),p=this,bn(rI).call(rI,p)||rI.push(p),a}catch(e){const t=Array.isArray(e)?e[0]:e;throw t&&t.code===Hg.OPERATION_ABORTED?jC.warning(\"[\".concat(this._clientId,\"] join number: \").concat(s,\", Joining channel failed, rollback\"),t):jC.error(\"[\".concat(this._clientId,\"] join number: \").concat(s,\", Joining channel failed, rollback\"),t),t.code!==Hg.OPERATION_ABORTED&&this._numberOfJoinCount===s&&(this._gateway.state=\"DISCONNECTED\",this._reset()),d.onError(t),t}var p}_joinGateway(){if(!this._joinInfo||!this._key)throw new LI(Hg.INVALID_OPERATION);return this._gateway.join(this._joinInfo,this._key,!(\"disabled\"!==this._joinInfo.cloudProxyServer||this._joinInfo.proxyServer||!RC(\"JOIN_WITH_FALLBACK_SIGNAL_PROXY\"))).then((e=>e)).catch((e=>{if(e.code===Hg.INIT_WEBSOCKET_TIMEOUT)return this._gateway.leave(!0,ET.FALLBACK),e;if(e.code===Hg.INIT_DATACHANNEL_TIMEOUT)return this._gateway.leave(!0,ET.FALLBACK),e;throw e})).then((e=>{if(e instanceof LI){if(e.code===Hg.INIT_WEBSOCKET_TIMEOUT){if(jC.info(\"[\".concat(this._clientId,\"] join timeout, fallback to proxy\")),!this._joinInfo||!this._key)throw new LI(Hg.INVALID_OPERATION);this._joinInfo.cloudProxyServer=\"fallback\",this._cloudProxyServerMode=\"fallback\",this.store.cloudProxyServerMode=\"fallback\";const e=RC(\"PROXY_SERVER_TYPE3\");if(Array.isArray(e))if(this._joinInfo.apUrl){const t=/^https?:\\/\\/(.+?)(\\/.*)?$/.exec(this._joinInfo.apUrl)[1].split(\".\"),i=t.slice(t.length-2).join(\".\");e.forEach((e=>{this._joinInfo&&bn(e).call(e,i)&&(this._joinInfo.proxyServer=e)})),this._joinInfo.proxyServer||(this._joinInfo.proxyServer=e[0])}else this._joinInfo.proxyServer=e[0];else this._joinInfo.proxyServer=e;const t=RC(\"LOG_UPLOAD_SERVER\").match(/.+:(\\d{1,5})$/);t&&t[1]&&\"443\"!==t[1]&&jC.setProxyServer(this._joinInfo.proxyServer),\"443\"!==RC(\"STATS_COLLECTOR_PORT\").toString()&&eI.setProxyServer(this._joinInfo.proxyServer);return eI.reportApiInvoke(this._sessionId,{name:hT.JOIN_FALLBACK_TO_PROXY,options:[this._joinInfo.proxyServer],tag:pT.TRACER}).onSuccess(),this.safeEmit(mT.JOIN_FALLBACK_TO_PROXY,this._joinInfo.proxyServer),RC(\"JOIN_WITH_FALLBACK_MEDIA_PROXY_FORCE\")&&this._joinInfo.turnServer.servers.forEach((e=>{\"forceturn\"in e&&(e.forceturn=!0)})),this._gateway.join(this._joinInfo,this._key)}if(jC.info(\"[\".concat(this._clientId,\"] join by datachannel timeout, fallback to websocket\")),!this._joinInfo||!this._key)throw new LI(Hg.INVALID_OPERATION);return eI.reportApiInvoke(this._sessionId,{name:hT.DATACHANNEL_FAILBACK,options:[this.store.clientId],tag:pT.TRACER}).onSuccess(),this._joinGateway()}return e})).then((e=>e))}async leave(){jC.info(\"[\".concat(this._clientId,\"] Leaving channel\")),window.removeEventListener(bg()?\"beforeunload\":\"pagehide\",this._handleBeforeUnload),this._reset(),function(e){const t=rI.indexOf(e);-1!==t&&rI.splice(t,1)}(this);const e=await this._leaveMutex.lock();if(\"DISCONNECTED\"===this.connectionState)return jC.info(\"[\".concat(this._clientId,\"] Leaving channel repeated, success\")),void e();await this._gateway.leave(\"CONNECTED\"!==this.connectionState),jC.info(\"[\".concat(this._clientId,\"] Leaving channel success\")),this._joinAndNotLeaveYet=!1,this.store.resetJoinChannelServiceRecords(),e()}async publish(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!Array.isArray(e)){if(!(e instanceof lb))return this._publishDataChannel(e);e=[e]}if(0===e.length)throw new LI(Hg.INVALID_PARAMS,\"param list is empty\");const i=e;if(\"audience\"===this._gateway.role)throw new LI(Hg.INVALID_OPERATION,\"audience can not publish stream\");for(const e of i){if(!(e instanceof lb))throw new LI(Hg.INVALID_PARAMS,\"parameter is not local track\");if(!e._enabled&&t)throw new LI(Hg.TRACK_IS_DISABLED,\"can not publish a disabled track: \".concat(e.getTrackId()))}jC.info(\"[\".concat(this._clientId,\"] Publishing tracks, id \").concat(i.map((e=>\"\".concat(e.getTrackId(),\" \")))));const n=await this._publishMutex.lock();await this._configDistribute.awaitConfigDistributeComplete(),t&&i.forEach((e=>{const t=this._configDistribute.getBitrateLimit();e instanceof Rw&&t&&e.setBitrateLimit(t.uplink)}));try{await this._publishHighStream(i),jC.info(\"[\".concat(this._clientId,\"] Publish success, id \").concat(i.map((e=>\"\".concat(e.getTrackId(),\" \")))))}catch(e){throw jC.error(\"[\".concat(this._clientId,\"] publish error\"),e.toString()),e}finally{n()}}async _publishDataChannel(e){zg(e.id,\"id\",0,65535,!0),Yg(e.ordered,\"ordered\"),Xg(e.metadata,\"metadata\",0,512),jC.info(\"[\".concat(this._clientId,\"] Publishing datachannels, id \").concat(e.id));const t=await this._publishMutex.lock();try{if(-1!==this._p2pChannel.getAllDataChannels().findIndex((t=>t.id===e.id)))throw new LI(Hg.INVALID_PARAMS,\"Invalid id: \".concat(e.id,\". If you want to republish the datachannel, unpublish first\"));if(!this._joinInfo||void 0===this._uid)throw new LI(Hg.INVALID_OPERATION,\"Can't publish datachannel, haven't joined yet!\");if(\"CONNECTED\"!==this.connectionState&&\"RECONNECTING\"!==this.connectionState)throw new LI(Hg.INVALID_OPERATION,\"can not publish datachannel in \".concat(this.connectionState,\" state\"));if(\"auto\"===this._turnServer.mode&&RC(\"FORCE_TURN\")&&!RC(\"TURN_ENABLE_TCP\")&&!RC(\"TURN_ENABLE_UDP\"))throw new LI(Hg.UNEXPECTED_ERROR,\"force TURN With No TURN Configuration\");const i=new aP(e);if(await this._p2pChannel.publishDataChannel([i]),!this._p2pChannel.isP2PDisconnected()){if(\"number\"!=typeof i._originDataChannelId)throw jC.error(\"[\".concat(this._clientId,\"] can not publish with mediaType datachannel, cannot get RTCDatachannel id\")),new LI(Hg.CREATE_DATACHANNEL_ERROR);try{const t={streamId:e.id,ordered:e.ordered,maxRetransmits:RC(\"DATASTREAM_MAX_RETRANSMITS\"),metadata:e.metadata,channelId:i._originDataChannelId};await this._gateway.publishDataChannel(this._uid,t,!0),await i._waitTillOpen()}catch(e){if(e.code!==Hg.DISCONNECT_P2P)throw e}}return jC.info(\"[\".concat(this._clientId,\"] Publish dataChannels success, id \").concat(i.id)),i}catch(e){throw jC.error(\"[\".concat(this._clientId,\"] publish datachannels error\"),e.toString()),e}finally{t()}}async unpublish(e){if(!this._joinInfo||void 0===this._uid)throw new LI(Hg.INVALID_OPERATION,\"Can't unpublish stream, haven't joined yet!\");let t=[];if(e)if(Array.isArray(e))t=e;else{if(!(e instanceof lb))return this._unpublishDataChannel([e]);t=[e]}else this.store.useP2P||await this._unpublishDataChannel(),t=this._p2pChannel.getAllTracks(!0);jC.info(\"[\".concat(this._clientId,\"] Unpublish tracks, tracks \").concat(t.map((e=>\"\".concat(e.getTrackId(),\" \"))),\" \"));const i=await this._publishMutex.lock();try{if(this._p2pChannel instanceof hV){const e=await this._p2pChannel.unpublish(t);e&&await this._gateway.sendExtensionMessage(vv.UNPUBLISH,{unpubMsg:e},!0)}else{const e=await this._p2pChannel.unpublish(t);e&&await this._gateway.unpublish(e,this._uid),jC.info(\"[\".concat(this._clientId,\"] Unpublish success,tracks \").concat(t.map((e=>\"\".concat(e.getTrackId())))))}}catch(e){throw jC.error(\"[\".concat(this._clientId,\"] unpublish error\"),e.toString()),e}finally{i&&i()}}async _unpublishDataChannel(e){void 0!==e&&0!==e.length||(e=this._p2pChannel.getAllDataChannels()),jC.info(\"[\".concat(this._clientId,\"] Unpublish datachannels, datachannels \").concat(e.map((e=>\"\".concat(e.id,\" \"))),\" \"));const t=await this._publishMutex.lock();try{const i=await this._p2pChannel.unpublishDataChannel(e);i&&await this._gateway.unpublishDataChannel(i),jC.info(\"[\".concat(this._clientId,\"] Unpublish dataChannel success,dataChannel \").concat(e.map((e=>\"\".concat(e.id)))))}catch(e){throw jC.error(\"[\".concat(this._clientId,\"] unpublish dataChannel error\"),e.toString()),e}finally{t&&t()}}async subscribe(e,t,i){return\"datachannel\"===t?this._subscribeDataChannel(e,i):this._subscribe(e,t)}async presubscribe(e,t){if(qg(t,\"mediaType\",[\"audio\",\"video\"]),this._p2pChannel instanceof hV)throw new LI(Hg.INVALID_OPERATION,\"can't presub at p2p mode\");if(!this._joinInfo)throw new LI(Hg.INVALID_OPERATION,\"can't presub when not join\");if(\"CONNECTED\"!==this.connectionState&&\"RECONNECTING\"!==this.connectionState)throw new LI(Hg.INVALID_OPERATION,\"can't presub in \".concat(this.connectionState,\" state\"));const i=t===av.AUDIO,n=t===av.VIDEO,r=await this._subscribeMutex.lock();try{const{ssrcId:s,ortc:o,rtxSsrcId:a,cname:c,uint_id:d}=await this._gateway.presubscribe(e,t,!0);if(null==s)throw new LI(Hg.UNEXPECTED_RESPONSE,\"no ssrc id\");let l=this._users.find((t=>t.uid===e));l||(l=new sV(e,d||e),l._is_pre_created=!0,this._users.push(l)),c&&(l._cname=c),l._uintid||(l._uintid=d||e),i&&(l._audioSSRC=s,l._audio_pre_subscribed=!0,o&&(l._audioOrtc=o)),n&&(l._videoSSRC=s,l._video_pre_subscribed=!0,o&&(l._videoOrtc=o),null!=a&&(l._rtxSsrcId=a)),jC.info(\"[\".concat(this._clientId,\"] presub succeed ssrc: \").concat(s)),await this._p2pChannel.subscribe(l,t,s,a,o);const u=i?l._audioTrack:l._videoTrack;if(!u)throw new LI(Hg.UNEXPECTED_ERROR,\"can not find remote track in user\");return i&&(l._trust_audio_stream_added_state_=!0,l._audio_added_=!0),n&&(l._trust_video_stream_added_state_=!0,l._video_added_=!0),u}catch(t){throw jC.error(\"[\".concat(this._clientId,\"] presub user \").concat(e,\" error\"),t),t}finally{r()}}async _subscribeDataChannel(e,t){var i;if(zg(t,\"channelId\",0,65535,!0),!this._joinInfo)throw new LI(Hg.INVALID_OPERATION,\"Can't subscribe datachannel, not joined\");if(\"CONNECTED\"!==this.connectionState&&\"RECONNECTING\"!==this.connectionState)throw new LI(Hg.INVALID_OPERATION,\"Can't subscribe datachannel in \".concat(this.connectionState,\" state\"));if(!this._users.find((t=>t===e)))throw jC.error(\"[\".concat(this._clientId,\"] can not subscribe \").concat(e.uid,\", this user is not in the channel\")),new LI(Hg.INVALID_REMOTE_USER,\"user is not in the channel\");if(!e.hasAudio&&!e.hasVideo&&0===e._dataChannels.length)throw jC.error(\"[\".concat(this._clientId,\"] can not subscribe \").concat(e.uid,\", user is not published\")),new LI(Hg.INVALID_REMOTE_USER,\"user is not published\");const n=null===(i=e._dataChannels)||void 0===i?void 0:i.find((e=>e.id===t));if(!n)throw jC.error(\"[\".concat(this._clientId,\"] can not subscribe \").concat(e.uid,\" with mediaType datachannel, remote datachannel is not published\")),new LI(Hg.REMOTE_USER_IS_NOT_PUBLISHED);const r=await this._subscribeMutex.lock();jC.info(\"[\".concat(this._clientId,\"] subscribe user \").concat(e.uid,\", mediaType: datachannel\"));try{const t=await this._p2pChannel.subscribeDataChannel(e,[n]);if(t&&bn(t).call(t,n.id))try{var s;if(\"number\"!=typeof n._originDataChannelId)throw jC.error(\"[\".concat(this._clientId,\"] can not subscribe \").concat(e.uid,\" with mediaType datachannel, cannot get RTCDatachannel\")),new LI(Hg.CREATE_DATACHANNEL_ERROR);const t={id:n.id,datachannelId:n._originDataChannelId,ordered:n.ordered,maxRetransmits:n.maxRetransmits,metadata:null!==(s=n.metadata)&&void 0!==s?s:\"\"};await this._gateway.subscribeDataChannel(e.uid,t,!0),await n._waitTillOpen()}catch(t){if((null==t?void 0:t.code)!==Hg.WS_ABORT)throw await this._p2pChannel.unsubscribeDataChannel(e,[n]),t;await this._p2pChannel.unsubscribeDataChannel(e,[n]),this._p2pChannel.setPendingRemoteDataChannel(e,n.id)}return jC.info(\"[\".concat(this._clientId,\"] subscribe success user \").concat(e.uid,\", mediaType: datachannel\")),n}finally{r()}}async _p2pSubscribe(e,t,i){if(qg(t,\"mediaType\",[\"audio\",\"video\"]),!this._joinInfo)throw new LI(Hg.INVALID_OPERATION,\"Can't subscribe stream, not joined\");if(\"CONNECTED\"!==this.connectionState&&\"RECONNECTING\"!==this.connectionState)throw new LI(Hg.INVALID_OPERATION,\"Can't subscribe stream in \".concat(this.connectionState,\" state\"));if(!this._users.find((t=>t===e))){const t=new LI(Hg.INVALID_REMOTE_USER,\"user is not in the channel\");throw jC.error(\"[\".concat(this._clientId,\"] can not subscribe \").concat(e.uid,\", this user is not in the channel\")),t}if(!e.hasAudio&&!e.hasVideo){const t=new LI(Hg.INVALID_REMOTE_USER,\"user is not published\");throw jC.error(\"[\".concat(this._clientId,\"] can not subscribe \").concat(e.uid,\", user is not published\")),t}if(!i&&(\"audio\"===t&&!e.hasAudio||\"video\"===t&&!e.hasVideo)){const i=new LI(Hg.REMOTE_USER_IS_NOT_PUBLISHED);throw jC.error(\"[\".concat(this._clientId,\"] can not subscribe \").concat(e.uid,\" with mediaType \").concat(t,\", remote track is not published\")),i}const n=await this._subscribeMutex.lock();jC.info(\"[\".concat(this._clientId,\"] subscribe user \").concat(e.uid,\", mediaType: \").concat(t));try{if(await this._p2pChannel.hasRemoteMediaWithLock(e,t))await this._p2pChannel.unmuteRemote(e,t);else try{const i=\"audio\"===t?e._audioSSRC:e._videoSSRC,n=\"audio\"===t?e._audioMid:e._videoMid;this.store.subscribe(e.uid,t,Date.now()),this._p2pChannel instanceof hV&&await this._p2pChannel.subscribe(e,t,i,n)}catch(e){throw e}jC.info(\"[\".concat(this._clientId,\"] subscribe success user \").concat(e.uid,\", mediaType: \").concat(t)),this._defaultStreamFallbackType&&this.setStreamFallbackOption(e.uid,this._defaultStreamFallbackType).catch((e=>{jC.warning(\"[\".concat(this._clientId,\"] auto set fallback failed\"),e)}));const i=\"audio\"===t?e._audioTrack:e._videoTrack;if(!i)throw new LI(Hg.UNEXPECTED_ERROR,\"can not find remote track in user object\");return i}catch(t){throw jC.error(\"[\".concat(this._clientId,\"] subscribe user \").concat(e.uid,\" error\"),t),t}finally{n()}}async _subscribe(e,t,i){if(this._p2pChannel instanceof hV)return this._p2pSubscribe(e,t);if(qg(t,\"mediaType\",[\"audio\",\"video\"]),!this._joinInfo)throw new LI(Hg.INVALID_OPERATION,\"Can't subscribe stream, not joined\");if(\"CONNECTED\"!==this.connectionState&&\"RECONNECTING\"!==this.connectionState)throw new LI(Hg.INVALID_OPERATION,\"Can't subscribe stream in \".concat(this.connectionState,\" state\"));if(!this._users.find((t=>t===e))){const t=new LI(Hg.INVALID_REMOTE_USER,\"user is not in the channel\");throw jC.error(\"[\".concat(this._clientId,\"] can not subscribe \").concat(e.uid,\", this user is not in the channel\")),t}if(!e.hasAudio&&!e.hasVideo){const t=new LI(Hg.INVALID_REMOTE_USER,\"user is not published\");throw jC.error(\"[\".concat(this._clientId,\"] can not subscribe \").concat(e.uid,\", user is not published\")),t}if(!(i||(\"audio\"!==t||e.hasAudio&&void 0!==e._audioSSRC)&&(\"video\"!==t||e.hasVideo&&void 0!==e._videoSSRC))){const i=new LI(Hg.REMOTE_USER_IS_NOT_PUBLISHED);throw jC.error(\"[\".concat(this._clientId,\"] can not subscribe \").concat(e.uid,\" with mediaType \").concat(t,\", remote track is not published\")),i}let n=\"audio\"===t?e._audioSSRC:e._videoSSRC,r=\"audio\"===t?e._audioOrtc:e._videoOrtc,s=\"video\"===t?e._rtxSsrcId:void 0,o={stream_type:\"audio\"===t?av.AUDIO:av.VIDEO,ssrcId:n};const a=await this._subscribeMutex.lock();jC.info(\"[\".concat(this._clientId,\"] subscribe user \").concat(e.uid,\", mediaType: \").concat(t));try{if(await this._p2pChannel.hasRemoteMediaWithLock(e,t))await this._p2pChannel.unmuteRemote(e,t);else try{const i=\"audio\"===t?e._audioSSRC:e._videoSSRC;void 0!==i&&i!==n&&(n=i,r=\"audio\"===t?e._audioOrtc:e._videoOrtc,s=\"video\"===t?e._rtxSsrcId:void 0,o={stream_type:\"audio\"===t?av.AUDIO:av.VIDEO,ssrcId:n}),RU.markSubscribeStart(this.store.clientId,n),this.store.subscribe(e.uid,t,Date.now()),await this._p2pChannel.subscribe(e,t,n,s,r);try{await this._gateway.subscribe(e.uid,o,!0)}catch(i){if((null==i?void 0:i.code)!==Hg.WS_ABORT)throw await this._p2pChannel.unsubscribe(e,t),i;await this._p2pChannel.unsubscribe(e,t,!0),this._p2pChannel.setPendingRemoteMedia(e,t)}this.store.subscribe(e.uid,t,void 0,Date.now()),this._p2pChannel.reportSubscribeEvent(!0,null,e,t)}catch(i){throw this._p2pChannel.reportSubscribeEvent(!1,null==i?void 0:i.code,e,t),i}jC.info(\"[\".concat(this._clientId,\"] subscribe success user \").concat(e.uid,\", mediaType: \").concat(t)),this._defaultStreamFallbackType&&this.setStreamFallbackOption(e.uid,this._defaultStreamFallbackType).catch((e=>{jC.warning(\"[\".concat(this._clientId,\"] auto set fallback failed\"),e)}));const i=\"audio\"===t?e._audioTrack:e._videoTrack;if(!i)throw new LI(Hg.UNEXPECTED_ERROR,\"can not find remote track in user object\");return i}catch(t){throw jC.error(\"[\".concat(this._clientId,\"] subscribe user \").concat(e.uid,\" error\"),t),t}finally{a()}}async massSubscribe(e){if(Qg(e,\"subscribeList\"),!this._joinInfo)throw new LI(Hg.INVALID_OPERATION,\"Can't subscribe stream, not joined\");if(\"CONNECTED\"!==this.connectionState&&\"RECONNECTING\"!==this.connectionState)throw new LI(Hg.INVALID_OPERATION,\"Can't subscribe stream in \".concat(this.connectionState,\" state\"));const t=Date.now(),i=new Map,n=await this._subscribeMutex.lock();jC.info(\"[\".concat(this._clientId,\"]start massSubscribe user \").concat(e.map((e=>{let{user:t,mediaType:i}=e;return\"user: \".concat(null==t?void 0:t.uid,\", mediaType: \").concat(i)})).join(\"; \")));const r=(e=[...e]).map((e=>{let{user:t,mediaType:i}=e;return{user:t,mediaType:i}})),s=await this._p2pChannel.globalLock();try{var o;for(let t=e.length-1;t>=0;t--){const n=e[t],{user:s,mediaType:o}=n;if(qg(o,\"mediaType\",[\"audio\",\"video\"]),!s){const e=new LI(Hg.INVALID_PARAMS,\"user property does not exist in subscribeList item\");throw jC.error(\"[\".concat(this._clientId,\"] user property does not exist in subscribeList item\")),e}if(!this._users.find((e=>e===s))){const i=new LI(Hg.INVALID_REMOTE_USER,\"user is not in the channel\");jC.error(\"[\".concat(this._clientId,\"] can not massSubscribe \").concat(s.uid,\", this user is not in the channel\")),r[t].error=i,e.splice(t,1);continue}if(\"audio\"===o&&(!s.hasAudio||void 0===s._audioSSRC)||\"video\"===o&&(!s.hasVideo||void 0===s._videoSSRC)){const i=new LI(Hg.REMOTE_USER_IS_NOT_PUBLISHED);jC.error(\"[\".concat(this._clientId,\"] can not subscribe \").concat(s.uid,\" with mediaType \").concat(o,\", remote user is not published\")),r[t].error=i,e.splice(t,1);continue}const a=ZI.Video|ZI.LwoVideo,c=i.get(s);if(c){if(\"video\"===o?c&a:c&ZI.Audio){e.splice(t,1),jC.warning(\"[\".concat(this._clientId,\"] repeat massSubscribe user:\").concat(s.uid,\", mediaType:\").concat(o,\" twice\"));continue}i.set(s,c|(\"video\"===o?a:ZI.Audio))}else i.set(s,\"video\"===o?a:ZI.Audio)}for(let t=e.length-1;t>=0;t--){const n=e[t],{user:r,mediaType:s}=n,o=ZI.Video|ZI.LwoVideo;if(this._p2pChannel.hasRemoteMedia(r,s)){await this._p2pChannel.unmuteRemoteNoLock(r,s);const n=i.get(r);i.set(r,\"video\"===s?n^o:n^ZI.Audio),e.splice(t,1)}}this.store.massSubscribe(e.map((e=>({userId:e.user.uid,type:e.mediaType}))),t);const a=BT(o=Array.from(i.entries())).call(o,((e,t)=>{let[i,n]=t;if(0===n)return e;const r={stream_id:i.uid,stream_type:n};return n&ZI.Audio&&(r.audio_ssrc=i._audioSSRC),n&ZI.Video&&(r.video_ssrc=i._videoSSRC),e.push(r),e}),[]);try{e.length>0&&await this._p2pChannel.massSubscribeNoLock(e.map((e=>{let{user:t,mediaType:i}=e;return{user:t,mediaType:i,ssrcId:i===av.VIDEO?t._videoSSRC:t._audioSSRC,rtxSsrcId:i===av.VIDEO?t._rtxSsrcId:void 0}})));const i=new Map;if(a.length>0){const e=await this._gateway.subscribeAll(a,!0);((null==e?void 0:e.users)||[]).forEach((e=>{let{stream_id:t,video_error_code:n,audio_error_code:r,error_code:s}=e;(n||r||s)&&i.set(t,{video_error_code:n,audio_error_code:r,error_code:s})}))}if(Array.from(i.entries()).length>0){const e=[];Array.from(i.entries()).forEach((t=>{let[i,n]=t;const r=this.remoteUsers.find((e=>e.uid===i));if(r){let t;n.error_code||n.video_error_code&&n.audio_error_code?t=void 0:n.video_error_code?t=av.VIDEO:n.audio_error_code&&(t=av.AUDIO),e.push({user:r,mediaType:t})}})),e.length>0&&await this._p2pChannel.massUnsubscribeNoLock(e)}for(const e of r){const t=i.get(e.user.uid);if(t){const i=t.error_code||\"audio\"===e.mediaType&&t.audio_error_code||\"video\"===e.mediaType&&t.video_error_code;if(i){const t=kv(i);jC.error(\"user:\".concat(e.user.uid,\" mediaType:\").concat(e.mediaType,\" has massSubscribe error \").concat(t.desc)),e.error=new LI(Hg.SUBSCRIBE_FAILED,\"code \".concat(i,\": \").concat(t.desc))}}e.error||(\"video\"===e.mediaType?e.track=e.user.videoTrack:e.track=e.user.audioTrack)}return this.store.massSubscribe(r.filter((e=>!e.error)).map((e=>({userId:e.user.uid,type:e.mediaType}))),void 0,Date.now()),r.forEach((e=>{var i;eI.subscribe(this.store.sessionId,{succ:!!e.error,ec:(null===(i=e.error)||void 0===i?void 0:i.code)||null,video:e.mediaType===av.VIDEO,audio:e.mediaType===av.AUDIO,peerid:e.user.uid,subscribeRequestid:e.mediaType===av.VIDEO?e.user._videoSSRC:e.user._audioSSRC,p2pid:this.store.p2pId,eventElapse:Math.floor(performance.now()-t)},!0)})),jC.info(\"[\".concat(this._clientId,\"] massSubscribe success \").concat(e.map((e=>{let{user:t,mediaType:i}=e;return\"user: \".concat(null==t?void 0:t.uid,\", mediaType: \").concat(i)})).join(\"; \"))),r}catch(t){throw await this._p2pChannel.massUnsubscribeNoLock(e),t}}finally{s(),n()}}async unsubscribe(e,t,i){if(t||this.store.useP2P){if(\"datachannel\"===t)return this._unsubscribeDataChannel(e,i)}else await this._unsubscribeDataChannel(e,i);if(t&&qg(t,\"mediaType\",[\"audio\",\"video\"]),!this._joinInfo)throw new LI(Hg.INVALID_OPERATION,\"Can't unsubscribe stream, haven't joined yet!\");if(!this._users.find((t=>t===e))){const t=new LI(Hg.INVALID_REMOTE_USER,\"user is not in the channel\");throw jC.error(\"[\".concat(this._clientId,\"] can not unsubscribe \").concat(e.uid,\", user is not in the channel\")),t}jC.info(\"[\".concat(this._clientId,\"] unsubscribe uid: \").concat(e.uid,\", mediaType: \").concat(t));const n=await this._subscribeMutex.lock();try{if(this._p2pChannel instanceof hV)await this._p2pChannel.unsubscribe(e,t);else{const i=await this._p2pChannel.unsubscribe(e,t);i&&await this._gateway.unsubscribe(i,e.uid),t&&\"audio\"!==t||(e._audio_pre_subscribed=!1),t&&\"video\"!==t||(e._video_pre_subscribed=!1),e._is_pre_created&&WT(this._users,e),jC.info(\"[\".concat(this._clientId,\"] unsubscribe success uid: \").concat(e.uid,\", mediaType: \").concat(t))}}catch(t){if(t.code===Hg.DISCONNECT_P2P)return void jC.warning(\"disconnecting p2p, abort unsubscribe request.\");throw jC.error(\"[\".concat(this._clientId,\"] unsubscribe user \").concat(e.uid,\" error\"),t.toString()),t}finally{n()}}async _unsubscribeDataChannel(e,t){if(t&&zg(t,\"id\",0,65535,!0),!this._joinInfo)throw new LI(Hg.INVALID_OPERATION,\"Can't unsubscribe datachannel, haven't joined yet!\");if(!this._users.find((t=>t===e))){const t=new LI(Hg.INVALID_REMOTE_USER,\"user is not in the channel\");throw jC.error(\"[\".concat(this._clientId,\"] can not unsubscribe \").concat(e.uid,\", user is not in the channel\")),t}let i;if(\"number\"==typeof t){const n=e._dataChannels.find((e=>e.id===t));n&&(i=[n])}else i=e._dataChannels;if(void 0===i){const i=new LI(Hg.REMOTE_USER_IS_NOT_PUBLISHED);throw jC.error(\"[\".concat(this._clientId,\"] can not unsubscribe \").concat(e.uid,\" with channelId \").concat(t,\", remote datachannel is not published\")),i}jC.info(\"[\".concat(this._clientId,\"] unsubscribe uid: \").concat(e.uid,\", mediaType: datachannel, ids: \").concat(i.map((e=>e.id))));try{const t=await this._p2pChannel.unsubscribeDataChannel(e,i);t&&await this._gateway.unsubscribeDataChannel(t,e.uid),jC.info(\"[\".concat(this._clientId,\"] unsubscribe datachannel success uid: \").concat(e.uid,\", mediaType: datachannel, ids: \").concat(t))}catch(t){if(t.code===Hg.DISCONNECT_P2P)return void jC.warning(\"disconnecting p2p, abort unsubscribe request.\");throw jC.error(\"[\".concat(this._clientId,\"] unsubscribe user \").concat(e.uid,\" error\"),t.toString()),t}}async massUnsubscribe(e){if(Qg(e,\"unsubscribeList\"),!this._joinInfo)throw new LI(Hg.INVALID_OPERATION,\"Can't unsubscribeAll stream, haven't joined yet!\");jC.info(\"[\".concat(this._clientId,\"] start massUnsubscribe \").concat(e.map((e=>{let{user:t,mediaType:i}=e;return\"user: \".concat(null==t?void 0:t.uid,\", mediaType: \").concat(i,\";\")})).join())),e=[...e];const t=new Map;for(let i=e.length-1;i>=0;i--){const{user:n,mediaType:r}=e[i];if(!n){const e=new LI(Hg.INVALID_PARAMS,\"user property does not exist in unsubscribeList item\");throw jC.error(\"[\".concat(this._clientId,\"] user property does not exist in unsubscribeList item\")),e}qg(r,\"mediaType\",[\"video\",\"audio\",void 0]);if(!this._users.find((e=>e===n))){jC.warning(\"[\".concat(this._clientId,\"] can not unsubscribe \").concat(n.uid,\", user is not in the channel\")),e.splice(i,1);continue}const s=ZI.Video|ZI.LwoVideo;if(t.has(n)){const o=t.get(n);let a;switch(r){case\"video\":a=o&s;break;case\"audio\":a=o&ZI.Audio;break;default:a=o&(ZI.Audio|s)}if(a){jC.warning(\"[\".concat(this._clientId,\"] repeat massUnsubscribe user:\").concat(n.uid,\",mediaType:\").concat(r,\" twice.\")),e.splice(i,1);continue}r?\"audio\"===r?t.set(n,o|ZI.Audio):\"video\"===r&&t.set(n,o|s):t.set(n,o|ZI.Audio|s)}else r?\"audio\"===r?t.set(n,ZI.Audio):\"video\"===r&&t.set(n,s):t.set(n,ZI.Audio|s)}try{const t=await this._p2pChannel.massUnsubscribe(e);t&&await this._gateway.massUnsubscribe(t),jC.info(\"[\".concat(this._clientId,\"] massUnsubscribe success \").concat(e.map((e=>{let{user:t,mediaType:i}=e;return\"user: \".concat(null==t?void 0:t.uid,\", mediaType: \").concat(i,\";\")})).join()))}catch(e){if(e.code===Hg.DISCONNECT_P2P)return void jC.warning(\"[\".concat(this._clientId,\"] disconnecting p2p, abort unsubscribe request.\"));throw jC.error(\"[\".concat(this._clientId,\"] massUnsubscribe error\"),e.toString()),e}}async setLowStreamParameter(e){!function(e){if(!e)throw new Kg(Hg.INVALID_PARAMS);Zg(e.width)||Jg(e.width,\"streamParameter.width\"),Zg(e.height)||Jg(e.height,\"streamParameter.height\"),Zg(e.framerate)||Jg(e.framerate,\"streamParameter.framerate\"),Zg(e.bitrate)||zg(e.bitrate,\"streamParameter.bitrate\")}(e),(!e.width&&e.height||e.width&&!e.height)&&jC.warning(\"[\".concat(this._clientId,\"] The width and height parameters take effect only when both are set\")),jC.info(\"[\".concat(this._clientId,\"] set low stream parameter to\"),JSON.stringify(e));const t=this._configDistribute.getLowStreamConfigDistribute();if(t&&t.bitrate&&e.bitrate&&t.bitrate1e3+t.rttMs+100?this.ntpAlignErrorCount+=1:this.ntpAlignErrorCount=0,this.ntpAlignErrorCount>=3?i:0}getNtpWallTimeInMs(){return\"visible\"===document.visibilityState&&(this.remoteInboundOffset=this.getRemoteInboundOffset()),this.remoteInboundOffset+Date.now()+this._gateway.ntpOffset}setProxyServer(e,t){if(Xg(e,\"proxyServer\"),!t){if(\"DISCONNECTED\"!==this.connectionState)throw new LI(Hg.INVALID_OPERATION,\"Set proxy server before join channel\");if(\"disabled\"!==this._cloudProxyServerMode||this._useLocalAccessPoint)throw new LI(Hg.INVALID_OPERATION,\"You have already set the proxy\")}this._proxyServer=e,eI.setProxyServer(this._proxyServer),jC.setProxyServer(this._proxyServer),jC.info(\"[\".concat(this._clientId,\"] Set proxy server \").concat(t?\"by initialize call\":\"\",\" success.\"))}setTurnServer(e,t){if(Array.isArray(e)||(e=[e]),!t){if(\"DISCONNECTED\"!==this.connectionState)throw new LI(Hg.INVALID_OPERATION,\"Set turn server before join channel\");if(\"disabled\"!==this._cloudProxyServerMode||this._useLocalAccessPoint)throw new LI(Hg.INVALID_OPERATION,\"You have already set the proxy\")}if(RT(e))return this._turnServer={servers:e,mode:\"original-manual\"},void jC.info(\"[\".concat(this._clientId,\"] Set original turnserver \").concat(t?\"by initialize call\":\"\",\" success: \").concat(e.map((e=>e.urls)).join(\",\"),\".\"));e.forEach((e=>CT(e))),this._turnServer={servers:e,mode:\"manual\"},jC.info(\"[\".concat(this._clientId,\"] Set turnserver \").concat(t?\"by initialize call\":\"\",\" success.\"))}setLicense(e){if(\"DISCONNECTED\"!==this.connectionState){throw new LI(Hg.INVALID_OPERATION,\"you should set license before join channel\")}if(Xg(e,\"license\",32,32),!/^[A-Za-z\\d]+$/.test(e))throw new LI(Hg.INVALID_PARAMS,\"license should only contains characters from A-Z a-z 0-9\");this._license=e,jC.info(\"[\".concat(this._clientId,\"] set license success\"),e)}startProxyServer(e){if(\"DISCONNECTED\"!==this.connectionState)throw new LI(Hg.INVALID_OPERATION,\"Start proxy server before join channel\");if(this._proxyServer||\"manual\"===this._turnServer.mode||this._useLocalAccessPoint)throw new LI(Hg.INVALID_OPERATION,\"You have already set the proxy\");const t=[3,4,5];let i;switch(void 0===e&&(e=3),e){case 1:case 2:throw new LI(Hg.NOT_SUPPORTED,\"proxy mode 1/2 has been deprecated and not supported.\");case 3:i=\"proxy3\";break;case 4:i=\"proxy4\";break;case 5:i=\"proxy5\";break;default:throw new LI(Hg.INVALID_PARAMS,\"proxy server mode must be \".concat(t.join(\"|\")))}this._cloudProxyServerMode=i,this.store.cloudProxyServerMode=i,jC.info(\"[\".concat(this._clientId,\"] set cloud proxy server mode to\"),this._cloudProxyServerMode)}stopProxyServer(){if(\"DISCONNECTED\"!==this.connectionState)throw new LI(Hg.INVALID_OPERATION,\"Stop proxy server after leave channel\");eI.setProxyServer(),jC.setProxyServer(),this._cloudProxyServerMode=\"disabled\",this.store.cloudProxyServerMode=\"disabled\",jC.info(\"[\".concat(this._clientId,\"] set cloud proxy server mode to\"),this._cloudProxyServerMode),this._proxyServer=void 0,this._turnServer={mode:\"auto\",servers:[]}}setLocalAccessPointsV2(e){if(!e.accessPoints)throw new LI(Hg.INVALID_PARAMS,\"accessPoints is required.\");Qg(e.accessPoints.serverList,\"accessPoints.serverList\"),Xg(e.accessPoints.domain,\"accessPoints.domain\");const t=(e,t)=>{zg(e,t,0,65535,!0)};let i=443;if(e.accessPoints.port&&(t(e.accessPoints.port,\"accessPoints.port\"),i=e.accessPoints.port),this._proxyServer||\"disabled\"!==this._cloudProxyServerMode)throw new LI(Hg.INVALID_OPERATION,\"set local access point failed, You have already set the cloud proxy\");RC(\"CLOSE_AFB_FOR_LOCAL_AP\")&&(SC(\"JOIN_WITH_FALLBACK_SIGNAL_PROXY\",!1),SC(\"JOIN_WITH_FALLBACK_MEDIA_PROXY\",!1));const n=/^((\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\.){3}(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])$/,r=e.accessPoints.domain,s=e.accessPoints.serverList.map((e=>n.test(e)?\"\".concat(e.replace(/\\./g,\"-\"),\".\").concat(r):e)),o=s.map((e=>\"\".concat(e,\":\").concat(i)));this._useLocalAccessPoint=!0,this._setLocalAPVersion=2,SC(\"WEBCS_DOMAIN\",o),SC(\"WEBCS_DOMAIN_BACKUP_LIST\",o),SC(\"GATEWAY_DOMAINS\",[r]),e.report&&e.report.hostname&&Array.isArray(e.report.hostname)&&e.report.hostname.length?(Qg(e.report.hostname,\"report.hostname\"),SC(\"EVENT_REPORT_DOMAIN\",e.report.hostname[0]),SC(\"EVENT_REPORT_BACKUP_DOMAIN\",e.report.hostname[1]||e.report.hostname[0])):(SC(\"EVENT_REPORT_DOMAIN\",s[0]),SC(\"EVENT_REPORT_BACKUP_DOMAIN\",s[1]||s[0]));let a=6443;e.report&&e.report.port&&(t(e.report.port,\"report.port\"),a=e.report.port),SC(\"STATS_COLLECTOR_PORT\",a),e.report?SC(\"ENABLE_EVENT_REPORT\",!0):SC(\"ENABLE_EVENT_REPORT\",!1);let c=\"\";e.log&&e.log.hostname&&Array.isArray(e.log.hostname)&&e.log.hostname.length?(Qg(e.log.hostname,\"log.hostname\"),c=e.log.hostname[0]):c=s[0];let d=6444;e.log&&e.log.port&&(t(e.log.port,\"log.port\"),d=e.log.port),SC(\"LOG_UPLOAD_SERVER\",\"\".concat(c,\":\").concat(d));let l=[];e.cds&&e.cds.hostname&&Array.isArray(e.cds.hostname)&&e.cds.hostname.length?(Qg(e.cds.hostname,\"cds.hostname\"),l=e.cds.hostname):l=s;let u=443;e.cds&&e.cds.port&&(t(e.cds.port,\"cds.port\"),u=e.cds.port),SC(\"CDS_AP\",l.map((e=>\"\".concat(e,\":\").concat(u)))),e.cds?SC(\"ENABLE_CONFIG_DISTRIBUTE\",!0):SC(\"ENABLE_CONFIG_DISTRIBUTE\",!1),jC.info(\"set local access point v2 success\")}setLocalAccessPoints(e,t){if(Qg(e,\"serverList\"),Xg(t,\"domain\"),this._proxyServer||\"disabled\"!==this._cloudProxyServerMode)throw new LI(Hg.INVALID_OPERATION,\"set local access point failed, You have already set the cloud proxy\");const i=/^(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])$/;e=e.map((e=>i.test(e)?\"\".concat(e.replace(/\\./g,\"-\"),\".\").concat(t):e)),this._useLocalAccessPoint=!0,this._setLocalAPVersion=1,SC(\"WEBCS_DOMAIN\",e),SC(\"WEBCS_DOMAIN_BACKUP_LIST\",e),SC(\"GATEWAY_DOMAINS\",[t]),SC(\"EVENT_REPORT_DOMAIN\",e[0]),SC(\"EVENT_REPORT_BACKUP_DOMAIN\",e[1]||e[0]),SC(\"LOG_UPLOAD_SERVER\",\"\".concat(e[0],\":6444\")),jC.info(\"[\".concat(this._clientId,\"] set local access point success\"))}async setRemoteDefaultVideoStreamType(e){if(qg(e,\"streamType\",[0,1]),this._remoteDefaultVideoStreamType=e,this._joinInfo)try{await this._gateway.setDefaultRemoteVideoStreamType(e),this._joinInfo.defaultVideoStream=this._remoteDefaultVideoStreamType}catch(e){throw jC.error(\"[\".concat(this._clientId,\"] set default remote video stream type error\"),e.toString()),e}else jC.debug(\"[\".concat(this._clientId,\"] haven't joined yet, cache remoteDefaultVideoStreamType \").concat(e))}async setRemoteVideoStreamType(e,t){qg(t,\"streamType\",[0,1]);try{await this._gateway.setRemoteVideoStreamType(e,t),setTimeout((()=>{const t=this._users.find((t=>t.uid===e));t&&t.videoTrack&&t.videoTrack.updateMediaStreamTrackResolution()}),2e3)}catch(e){throw jC.error(\"[\".concat(this._clientId,\"] set remote video stream type error\"),e.toString()),e}jC.info(\"[\".concat(this._clientId,\"] set remote \").concat(e,\" video stream type to \").concat(t)),this._remoteStreamTypeCacheMap.set(e,t)}async setStreamFallbackOption(e,t){qg(t,\"fallbackType\",[0,1,2]);try{await this._gateway.setStreamFallbackOption(e,t)}catch(e){throw jC.error(\"[\".concat(this._clientId,\"] set stream fallback option\"),e.toString()),e}jC.info(\"[\".concat(this._clientId,\"] set remote \").concat(e,\" stream fallback type to \").concat(t)),this._streamFallbackTypeCacheMap.set(e,t)}setEncryptionConfig(e,t,i,n){!function(e){qg(e,\"encryptionMode\",[\"aes-128-xts\",\"aes-256-xts\",\"aes-128-ecb\",\"sm4-128-ecb\",\"aes-128-gcm\",\"aes-256-gcm\",\"aes-128-gcm2\",\"aes-256-gcm2\",\"none\"])}(e),Xg(t,\"secret\");const r=[\"aes-128-gcm2\",\"aes-256-gcm2\"];if(bn(r).call(r,e)){if(!i||!(i instanceof Uint8Array&&32===i.length))throw new LI(Hg.INVALID_PARAMS,\"salt must be an Uint8Array and exactly equal to 32 bytes\")}else if(i)throw new LI(Hg.INVALID_PARAMS,\"current encrypt mode does not need salt\");if(n){if(Yg(n,\"encryptDataStream\"),!bn(r).call(r,e))throw new LI(Hg.INVALID_PARAMS,\"current encrypt mode does not support data stream\");this._encryptDataStream=!0}new RegExp(\"^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*,.<>?/:;'\\\"|{}\\\\[\\\\]])(?=.{8,})\").test(t)||jC.warning(\"The secret is not strong:\\n The secret must contain at least 1 lowercase alphabetical character,\\n The secret must contain at least 1 uppercase alphabetical character,\\n The secret must contain at least 1 numeric character,\\n The secret must contain at least one special character,\\n The secret must be eight characters or longer.\\n \"),this._encryptionMode=e,this._encryptionSecret=t,i&&(this._encryptionSalt=QT(i))}async renewToken(e){if(Xg(e,\"token\",1,2047),!this._key||!this._joinInfo)throw new LI(Hg.INVALID_OPERATION,\"renewToken should not be called before user join\");const t=this._key;this._key=e,this._joinInfo&&(this._joinInfo.token=e);const i=await this._renewTokenMutex.lock();try{if(RC(\"USE_NEW_TOKEN\")){jC.debug(\"[\".concat(this._clientId,\"] start renew token with ticket from unilbs\"));const t=await gA(this._joinInfo,this._axiosCancelSource.token,this._config.httpRetryConfig||ES);jC.debug(\"[\".concat(this._clientId,\"] get ticket from unilbs success\")),await this._gateway.renewToken({token:e,ticket:t})}else jC.debug(\"[\".concat(this._clientId,\"] start renew token without ticket\")),await this._gateway.renewToken({token:e});jC.debug(\"[\".concat(this._clientId,\"] renewToken success\"))}catch(e){throw this._key=t,this._joinInfo.token=t,jC.error(\"[\".concat(this._clientId,\"] renewToken failed\"),e.toString()),e}finally{i()}}enableAudioVolumeIndicator(){this._audioVolumeIndicationInterval?jC.warning(\"you have already enabled audio volume indicator!\"):this._audioVolumeIndicationInterval=window.setInterval((()=>{const e=this._p2pChannel.getAudioLevels();this.safeEmit(mT.VOLUME_INDICATOR,e)}),RC(\"AUDIO_VOLUME_INDICATION_INTERVAL\")||2e3)}getRTCStats(){const e=this._statsCollector.getRTCStats(),t=this._gateway.getInChannelInfo();return e.Duration=Math.round(t.duration/1e3),e}async startLiveStreaming(e,t){if(!t){if(\"h264\"!==this.codec)throw new LI(Hg.LIVE_STREAMING_INVALID_RAW_STREAM,\"raw streaming is only support h264\");if(!this._p2pChannel.hasLocalMedia())throw new LI(Hg.LIVE_STREAMING_INVALID_RAW_STREAM,\"can not find stream to raw streaming\")}if(this._liveRawStreamingClient&&this._liveRawStreamingClient.hasUrl(e)||this._liveTranscodeStreamingClient&&this._liveTranscodeStreamingClient.hasUrl(e))throw new LI(Hg.LIVE_STREAMING_TASK_CONFLICT);const i=t?RI.TRANSCODE:RI.RAW;return this._createLiveStreamingClient(i).startLiveStreamingTask(e,i)}setLiveTranscoding(e){return this._createLiveStreamingClient(RI.TRANSCODE).setTranscodingConfig(e)}async stopLiveStreaming(e){const t=[this._liveRawStreamingClient,this._liveTranscodeStreamingClient].filter((t=>t&&t.hasUrl(e)));if(!t.length)throw new LI(Hg.INVALID_PARAMS,\"can not find live streaming url to stop\");await cg.all(t.map((t=>t&&t.stopLiveStreamingTask(e))))}async addInjectStreamUrl(e,t){if(!this._joinInfo)throw new LI(Hg.INVALID_OPERATION,\"can not addInjectStreamUrl, no joininfo\");const i=this._createLiveStreamingClient(RI.INJECT);i.setInjectStreamConfig(t,0),await i.startLiveStreamingTask(e,RI.INJECT)}async removeInjectStreamUrl(){var e;const t=this._createLiveStreamingClient(RI.INJECT),i=Array.from(NI(e=t.streamingTasks).call(e)).find((e=>e.mode===RI.INJECT));if(!this._joinInfo||!i)throw new LI(Hg.INVALID_OPERATION,\"can remove addInjectStreamUrl, no joininfo or inject task\");await t.stopLiveStreamingTask(i.url)}async startChannelMediaRelay(e){vV(e);const t=this._createChannelMediaRelayClient();await t.startChannelMediaRelay(e)}async updateChannelMediaRelay(e){vV(e);const t=this._createChannelMediaRelayClient();await t.updateChannelMediaRelay(e)}async stopChannelMediaRelay(){const e=this._createChannelMediaRelayClient();await e.stopChannelMediaRelay(),this._statsCollector.onStatsChanged&&(this._statsCollector.onStatsChanged=void 0)}async sendStreamMessage(e){var t;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!this._joinInfo)throw new LI(Hg.INVALID_OPERATION,\"can not send data stream, not joined\");if((\"string\"==typeof e||e instanceof Uint8Array)&&(e={payload:e}),\"string\"==typeof e.payload){const t=new TextEncoder;e.payload=t.encode(e.payload)}let n=!1;this._encryptDataStream&&this._encryptDataStreamIv&&this._encryptDataStreamKey&&window.crypto.subtle&&bn(t=[\"aes-128-gcm2\",\"aes-256-gcm2\"]).call(t,this._encryptionMode)&&(n=!0,e.payload=await async function(e,t,i){var n;const r=BT(n=Array.from(i)).call(n,((e,t)=>e+t),0),s={serverTs:0,seq:LC++,length:i.length,checkSum:r},o=new Uint8Array(lS(r,2)),a=new ArrayBuffer(PC),c=new DataView(a);c.setUint32(0,s.serverTs),c.setUint16(4,s.seq),c.setUint16(6,s.length),c.setUint16(8,s.checkSum);const d=16-i.length%16;i=ZT(i,new Uint8Array(d));const l=await window.crypto.subtle.encrypt({name:\"AES-GCM\",iv:e,tagLength:OC,additionalData:o},t,i);return ZT(new Uint8Array(a),new Uint8Array(l))}(this._encryptDataStreamIv,this._encryptDataStreamKey,e.payload));if(new Blob([e.payload]).size>1024)throw new LI(Hg.INVALID_PARAMS,n?\"encrypted stream message out of range.\":\"stream message out of range.\");return this._gateway.signal.request(EI.DATA_STREAM,{payload:QT(e.payload),syncWithAudio:e.syncWithAudio,sendTs:Date.now()-RB},!i)}sendMetadata(e){if(!this._joinInfo)throw new LI(Hg.INVALID_OPERATION,\"can not send metadata, not joined\");if(new Blob([e]).size>1024)throw new LI(Hg.METADATA_OUT_OF_RANGE);return this._gateway.signal.request(EI.SEND_METADATA,{session_id:this._joinInfo.sid,metadata:QT(e)})}async sendCustomReportMessage(e){if(Array.isArray(e)||(e=[e]),e.forEach(HC),!this._joinInfo)throw new LI(Hg.INVALID_OPERATION,\"can not send custom report, not joined\");await eI.sendCustomReportMessage(this._joinInfo.sid,e)}getLocalAudioStats(){return this._statsCollector.getLocalAudioTrackStats()}getRemoteAudioStats(){return this._statsCollector.getRemoteAudioTrackStats()}getLocalVideoStats(){return this._statsCollector.getLocalVideoTrackStats()}getRemoteVideoStats(){return this._statsCollector.getRemoteVideoTrackStats()}getRemoteNetworkQuality(){return this._statsCollector.getRemoteNetworkQualityStats()}async pickSVCLayer(e,t){qg(t.spatialLayer,\"spatialLayer\",[0,1,2,3]),qg(t.temporalLayer,\"temporalLayer\",[0,1,2,3]);try{await this._gateway.pickSVCLayer(e,t)}catch(e){throw jC.error(\"[\".concat(this._clientId,\"] pick SVC layer failed\"),e.toString()),e}}async setRTMConfig(e){const{apRTM:t=!1,rtmFlag:i}=e;if(Yg(t,\"apRTM\"),zg(i,\"rtmFlag\",0),this._rtmConfig.apRTM=t,this._rtmConfig.rtmFlag=i,jC.debug(\"[\".concat(this._clientId,\"] setRTMconfig \").concat(JSON.stringify(e),\" in \").concat(this.connectionState,\" state\")),(\"CONNECTED\"===this.connectionState||\"RECONNECTING\"===this.connectionState)&&this._joinInfo)return this._joinInfo.apRTM=t,this._joinInfo.rtmFlag=i,this._gateway.setRTM2Flag(i)}_reset(){if(jC.debug(\"[\".concat(this._clientId,\"] reset client\")),this._axiosCancelSource.cancel(),this._axiosCancelSource=sC.CancelToken.source(),this._streamFallbackTypeCacheMap=new Map,this._remoteStreamTypeCacheMap=new Map,this._configDistribute.stopGetConfigDistribute(),this._joinInfo=void 0,this._proxyServer=void 0,this._defaultStreamFallbackType=void 0,this._sessionId=null,this.store.sessionId=null,this._statsCollector.reset(),this._key=void 0,this._appId=void 0,this._uid=void 0,this.store.uid=void 0,this._channelName=void 0,this._encryptionMode=\"none\",this._encryptionSecret=null,this._encryptionSalt=null,this._encryptDataStreamKey=null,this._encryptDataStreamIv=null,this._pendingPublishedUsers=[],this._users.forEach((e=>{e._audioTrack&&e._audioTrack._destroy(),e._videoTrack&&e._videoTrack._destroy(),e._dataChannels&&(e._dataChannels.forEach((e=>e._close())),e._dataChannels.length=0)})),this._users=[],this._audioVolumeIndicationInterval&&(window.clearInterval(this._audioVolumeIndicationInterval),this._audioVolumeIndicationInterval=void 0),\"fallback\"===this._cloudProxyServerMode&&(this._cloudProxyServerMode=\"disabled\",this.store.cloudProxyServerMode=\"disabled\"),this._p2pChannel.reset(),this._publishMutex=new pS(\"client-publish\"),this._subscribeMutex=new pS(\"client-subscribe\"),this._networkQualityInterval&&(window.clearInterval(this._networkQualityInterval),this._networkQualityInterval=void 0),this._injectStreamingClient&&(this._injectStreamingClient.terminate(),this._injectStreamingClient.removeAllListeners(),this._injectStreamingClient=void 0),this._liveRawStreamingClient&&(this._liveRawStreamingClient.terminate(),this._liveRawStreamingClient.removeAllListeners(),this._liveRawStreamingClient=void 0),this._liveTranscodeStreamingClient&&(this._liveTranscodeStreamingClient.terminate(),this._liveTranscodeStreamingClient.removeAllListeners(),this._liveTranscodeStreamingClient=void 0),this._channelMediaRelayClient&&(this._channelMediaRelayClient.dispose(),this._channelMediaRelayClient=void 0),this._inspect)try{this._inspect.close(),this._inspect=void 0}catch(e){}if(this._moderation)try{this.setImageModeration(!1)}catch(e){}}_startSession(e,t){var i;const n=e||rS();e?jC.debug(\"[\".concat(this._clientId,\"] new Session \").concat(n)):jC.debug(\"[\".concat(this._clientId,\"] renewSession \").concat(this._sessionId,\" => \").concat(n));const r=e?\"\":this._sessionId||\"\";this._sessionId=n,this.store.sessionId=n;const s={lts:(new Date).getTime(),mode:this.mode,stringUid:(null==t?void 0:t.stringUid)||(null===(i=this._joinInfo)||void 0===i?void 0:i.stringUid),channelProfile:\"live\"===this.mode?1:0,channelMode:0,isABTestSuccess:Number(this._configDistribute.isSuccess),lsid:r,clientRole:\"audience\"===this.role?2:1};t?eI.sessionInit(this._sessionId,DB({cname:t.channel,appid:t.appId},s)):this._joinInfo?eI.sessionInit(this._sessionId,DB({cname:this._joinInfo.cname,appid:this._joinInfo.appId},s)):this._gateway.joinInfo&&eI.sessionInit(this._sessionId,DB({cname:this._gateway.joinInfo.cname,appid:this._gateway.joinInfo.appId},s)),this._joinInfo&&(this._joinInfo.sid=n),this._gateway.joinInfo&&(this._gateway.joinInfo.sid=n)}async _publishHighStream(e){if(!this._joinInfo||void 0===this._uid)throw new LI(Hg.INVALID_OPERATION,\"Can't publish stream, haven't joined yet!\");if(\"CONNECTED\"!==this.connectionState&&\"RECONNECTING\"!==this.connectionState)throw new LI(Hg.INVALID_OPERATION,\"can not publish stream in \".concat(this.connectionState,\" state\"));if(\"auto\"===this._turnServer.mode&&RC(\"FORCE_TURN\")&&!RC(\"TURN_ENABLE_TCP\")&&!RC(\"TURN_ENABLE_UDP\"))throw new LI(Hg.UNEXPECTED_ERROR,\"force TURN With No TURN Configuration\");jC.debug(\"[\".concat(this._clientId,\"] publish high stream\"));try{const i=await this._p2pChannel.publish(e,this._isDualStreamEnabled,this._lowStreamParameter);if(this._p2pChannel instanceof hV){const e=(await i.next()).value;if(e){try{await this._gateway.sendExtensionMessage(vv.PUBLISH,e,!0)}catch(e){throw i.throw(e),e}await i.next()}this._p2pChannel.reportPublishEvent(!0,null)}else{const n=(await i.next()).value;if(n){var t;let e;try{e=await this._gateway.publish(this._uid,n,!0)}catch(e){if(e.code!==Hg.DISCONNECT_P2P)throw i.throw(e),e}await i.next((null===(t=e)||void 0===t?void 0:t.ortc)||[])}this._p2pChannel.reportPublishEvent(!0,null);for(const t of e)t instanceof Rw&&t._encoderConfig&&this._gateway.setVideoProfile(t._encoderConfig),!t.muted&&t.enabled||await this._p2pChannel.muteLocalTrack(t)}}catch(t){if(this._p2pChannel.reportPublishEvent(!1,null==t?void 0:t.code,e),(null==t?void 0:t.code)===Hg.WS_ABORT)return;throw t}}async _publishLowStream(){if(!this._joinInfo||void 0===this._uid)throw new LI(Hg.INVALID_OPERATION,\"Can't publish stream, haven't joined yet!\");if(\"CONNECTED\"!==this.connectionState&&\"RECONNECTING\"!==this.connectionState)throw new LI(Hg.INVALID_OPERATION,\"can not publish stream in \".concat(this.connectionState,\" state\"));jC.debug(\"[\".concat(this._clientId,\"] publish low stream\"));const e=this._configDistribute.getLowStreamConfigDistribute();e&&e.bitrate&&(this._lowStreamParameter||(this._lowStreamParameter={width:160,height:120,framerate:15,bitrate:50}),this._lowStreamParameter&&this._lowStreamParameter.bitrate&&e.bitratenew CV(this._joinInfo,this._config.websocketRetryConfig||ES,this._config.httpRetryConfig||ES),i=e=>{e.onLiveStreamError=(e,t)=>{eI.reportApiInvoke(this._sessionId,{name:hT.ON_LIVE_STREAM_ERROR,options:[e,t],tag:pT.TRACER}).onSuccess(),this.safeEmit(mT.LIVE_STREAMING_ERROR,e,t)},e.onLiveStreamWarning=(e,t)=>{eI.reportApiInvoke(this._sessionId,{name:hT.ON_LIVE_STREAM_WARNING,options:[e,t],tag:pT.TRACER}).onSuccess(),this.safeEmit(mT.LIVE_STREAMING_WARNING,e,t)},e.on(GI.REQUEST_WORKER_MANAGER_LIST,((e,t,i)=>{if(!this._joinInfo)return i(new LI(Hg.INVALID_OPERATION,\"can not find join info to get worker manager\"));mA(e,this._joinInfo,this._axiosCancelSource.token,ES).then(t).catch(i)}))};switch(e){case RI.RAW:return this._liveRawStreamingClient||(this._liveRawStreamingClient=t(),i(this._liveRawStreamingClient)),this._liveRawStreamingClient;case RI.TRANSCODE:return this._liveTranscodeStreamingClient||(this._liveTranscodeStreamingClient=t(),i(this._liveTranscodeStreamingClient)),this._liveTranscodeStreamingClient;case RI.INJECT:return this._injectStreamingClient||(this._injectStreamingClient=t(),this._injectStreamingClient.on(GI.REQUEST_WORKER_MANAGER_LIST,((e,t,i)=>{if(!this._joinInfo)return i(new LI(Hg.INVALID_OPERATION,\"can not find join info to get worker manager\"));mA(e,this._joinInfo,this._axiosCancelSource.token,ES).then(t).catch(i)})),this._injectStreamingClient.onInjectStatusChange=(e,t,i)=>{this.safeEmit(mT.INJECT_STREAM_STATUS,e,t,i)}),this._injectStreamingClient}}_createChannelMediaRelayClient(){if(!this._joinInfo){return new LI(Hg.INVALID_OPERATION,\"can not create channel media relay client, please join channel first\").throw()}if(!this._channelMediaRelayClient){const{sendResolutionWidth:e,sendResolutionHeight:t}=this.getLocalVideoStats(),i={width:e,height:t};this._channelMediaRelayClient=new AV(this._joinInfo,this._clientId,this._config.websocketRetryConfig||ES,this._config.httpRetryConfig||ES,i),this._channelMediaRelayClient.on(\"state\",(e=>{e===qI.RELAY_STATE_FAILURE&&this._channelMediaRelayClient&&this._channelMediaRelayClient.dispose(),this.safeEmit(mT.CHANNEL_MEDIA_RELAY_STATE,e)})),this._channelMediaRelayClient.on(\"event\",(e=>{this.safeEmit(mT.CHANNEL_MEDIA_RELAY_EVENT,e)})),this._statsCollector.onStatsChanged=(e,t)=>{var i;\"resolution\"===e&&(null===(i=this._channelMediaRelayClient)||void 0===i||i.setVideoProfile(t))}}return this._channelMediaRelayClient}_handleUpdateDataChannel(e,t){const{added:i,deleted:n}=e,r=[];Array.isArray(i)&&i.length>0&&i.forEach((e=>{const{uid:i,stream_id:n,ordered:s,max_retrans_times:o,metadata:a}=e,c=this._users.find((e=>e._uintid===i));if(!c)return void jC.error(\"[\".concat(this._clientId,\"] can not find target user!(on_add_data_channel)\"));jC.debug(\"[\".concat(this._clientId,\"] data_channel added with uid \").concat(i)),bn(r).call(r,c)||r.push(c),c._uintid||(c._uintid=i);if(!(-1!==c._dataChannels.findIndex((t=>t.id===e.stream_id)))){const e={id:n,ordered:!!s,maxRetransmits:o,metadata:a},i=new oP(e);c._dataChannels.push(i),jC.info(\"[\".concat(this._clientId,\"] remote user \").concat(c.uid,\" published datachannel\")),t||this.safeEmit(mT.USER_PUBLISHED,c,\"datachannel\",e)}this._p2pChannel.hasPendingRemoteDataChannel(c,e.stream_id)&&(jC.debug(\"[\".concat(this._clientId,\"] resubscribe datachannel for user \").concat(c.uid,\" after reconnect.\")),this._subscribeDataChannel(c,e.stream_id).catch((e=>{jC.error(\"[\".concat(this._clientId,\"] resubscribe datachannel error\"),e.toString())})))})),t&&(this.safeEmit(mT.PUBLISHED_USER_LIST,this._pendingPublishedUsers),this._pendingPublishedUsers=[]),Array.isArray(n)&&n.length>0&&n.forEach((e=>{const{uid:t,stream_id:i}=e,n=this._users.find((e=>e._uintid===t));if(!n)return void jC.error(\"[\".concat(this._clientId,\"] can not find target user!(on_delete_data_channel)\"));const r=n._dataChannels.find((t=>t.id===e.stream_id));r&&(jC.debug(\"[\".concat(this._clientId,\"] data_stream delete with uid \").concat(t)),this._p2pChannel.unsubscribeDataChannel(n,[r]).then((e=>{if(n._dataChannels=n._dataChannels.filter((e=>e!==r)),e)return this._gateway.unsubscribeDataChannel(e,n.uid)})),jC.info(\"[\".concat(this._clientId,\"] remote user \").concat(t,\" unpublished datachannel ,id:\").concat(r.id)),this.safeEmit(mT.USER_UNPUBLISHED,n,\"datachannel\",r._config))}))}_handleRemoveDataChannels(e){const t=this._users.find((t=>t.uid===e.uid));if(t){if(void 0!==t._dataChannels&&t._dataChannels.length>0){jC.debug(\"[\".concat(this._clientId,\"] datachannel removed with uid \").concat(e.uid));const i=()=>{jC.info(\"[\".concat(this._clientId,\"] remote user \").concat(t.uid,\" unpublished datachannel\")),t._dataChannels.forEach((e=>{this.safeEmit(mT.USER_UNPUBLISHED,t,\"datachannel\",e._config)}))};this._p2pChannel.unsubscribeDataChannel(t,t._dataChannels).then((e=>{if(e)return this._gateway.unsubscribeDataChannel(e,t.uid)})),i()}}else jC.warning(\"[\".concat(this._clientId,\"] can not find target user!(on_remove_datachannel)\"))}_handleGatewayEvents(){this._gateway.on(XI.DISCONNECT_P2P,(async()=>{await this._p2pChannel.disconnectForReconnect()})),this._gateway.on(XI.CONNECTION_STATE_CHANGE,((e,t,i)=>{var n;if(i===ET.FALLBACK)return;const r=()=>{this.safeEmit(mT.CONNECTION_STATE_CHANGE,e,t,i)};if(eI.reportApiInvoke(this._sessionId||(null===(n=this._gateway.joinInfo)||void 0===n?void 0:n.sid)||null,{name:hT.CONNECTION_STATE_CHANGE,options:[e,t,i],tag:pT.TRACER}).onSuccess(JSON.stringify({cur:e,prev:t,reason:i})),jC.info(\"[\".concat(this._clientId,\"] connection state change: \").concat(t,\" -> \").concat(e)),\"DISCONNECTED\"===e)return this._reset(),void r();if(\"RECONNECTING\"===e)this._users.forEach((e=>{e._trust_in_room_=!1,e._trust_audio_enabled_state_=!1,e._trust_video_enabled_state_=!1,e._trust_audio_mute_state_=!1,e._trust_video_mute_state_=!1,e._trust_audio_stream_added_state_=!1,e._trust_video_stream_added_state_=!1,e._is_pre_created||(e._audio_pre_subscribed||(e._audioSSRC=void 0,e._audioOrtc=void 0),e._video_pre_subscribed||(e._videoSSRC=void 0,e._videoOrtc=void 0,e._rtxSsrcId=void 0),e._cname=void 0)})),this._userOfflineTimeout&&window.clearTimeout(this._userOfflineTimeout),this._streamRemovedTimeout&&window.clearTimeout(this._streamRemovedTimeout),this._userOfflineTimeout=void 0,this._streamRemovedTimeout=void 0;else if(\"CONNECTED\"===e){var s;this._streamFallbackTypeCacheMap.forEach(((e,t)=>{this._gateway.setStreamFallbackOption(t,e).catch((e=>{jC.warning(\"[\".concat(this._clientId,\"] auto set stream fallback option failed\"),e)}))})),this._remoteStreamTypeCacheMap.forEach(((e,t)=>{this._gateway.setRemoteVideoStreamType(t,e).catch((e=>{jC.warning(\"[\".concat(this._clientId,\"] auto set remote stream type failed\"),e)}))})),void 0!==this._remoteDefaultVideoStreamType&&void 0===(null===(s=this._joinInfo)||void 0===s?void 0:s.defaultVideoStream)&&this.setRemoteDefaultVideoStreamType(this._remoteDefaultVideoStreamType).then((()=>{jC.debug(\"[\".concat(this._clientId,\"] setRemoteDefaultVideoStreamType after gateway connected\"))})).catch((e=>{jC.error(\"[\".concat(this._clientId,\"] setRemoteDefaultVideoStreamType after gateway failed, \").concat(e))})),this.store.useP2P||(this._p2pChannel.republish(),this._userOfflineTimeout=window.setTimeout((()=>{if(\"CONNECTED\"!==this.connectionState)return;this._userOfflineTimeout=void 0;this._users.filter((e=>!e._trust_in_room_)).forEach((e=>{jC.debug(\"[\".concat(this._clientId,\"] user offline timeout, emit user offline \").concat(e.uid)),this._handleUserOffline({uid:e.uid})}))}),3e3),this._streamRemovedTimeout=window.setTimeout((()=>{\"CONNECTED\"===this.connectionState&&(this._streamRemovedTimeout=void 0,this._users.forEach((e=>{e._trust_audio_mute_state_||(jC.debug(\"[\".concat(this._clientId,\"] auto dispatch audio unmute event \").concat(e.uid)),this._handleMuteStream(e.uid,av.AUDIO,!1)),e._trust_video_mute_state_||(jC.debug(\"[\".concat(this._clientId,\"] auto dispatch video unmute event \").concat(e.uid)),this._handleMuteStream(e.uid,av.VIDEO,!1)),e._trust_audio_enabled_state_||(jC.debug(\"[\".concat(this._clientId,\"] auto dispatch enable local audio \").concat(e.uid)),this._handleSetStreamLocalEnable(\"audio\",e.uid,!0)),e._trust_video_enabled_state_||(jC.debug(\"[\".concat(this._clientId,\"] auto dispatch enable local video \").concat(e.uid)),this._handleSetStreamLocalEnable(\"video\",e.uid,!0)),e._trust_video_stream_added_state_||(jC.debug(\"[\".concat(this._clientId,\"] auto dispatch reset video stream added \").concat(e.uid)),this._handleResetAddStream(e,\"video\")),e._trust_audio_stream_added_state_||(jC.debug(\"[\".concat(this._clientId,\"] auto dispatch reset audio stream added \").concat(e.uid)),this._handleResetAddStream(e,\"audio\")),e._video_added_||e._audio_added_||(jC.debug(\"[\".concat(this._clientId,\"] auto dispatch stream remove \").concat(e.uid)),this._handleRemoveStream({uid:e.uid,uint_id:e._uintid}))})))}),1e3))}r()})),this._gateway.on(XI.REQUEST_NEW_GATEWAY_LIST,((e,t)=>{if(!this._joinInfo)return t(new LI(Hg.UNEXPECTED_ERROR,\"can not recover, no join info\"));uA(this._joinInfo,this._axiosCancelSource.token,this._config.httpRetryConfig||ES,this.store).then((t=>{this._joinInfo&&(this._joinInfo.apResponse=t.gatewayInfo.res,this._joinInfo.gatewayAddrs=t.gatewayInfo.gatewayAddrs,this._joinInfo.uni_lbs_ip=t.gatewayInfo.uni_lbs_ip);const i=[];t.gatewayInfo.gatewayAddrs.forEach((e=>{let{address:t}=e;const[n,r]=t.split(\":\");this._joinInfo&&this._joinInfo.proxyServer?i.push({proxy:this._joinInfo.proxyServer,host:n,port:r}):i.push({host:n,port:r})})),e(i)})).catch(t)})),this._gateway.on(XI.NETWORK_QUALITY,(e=>{\"normal\"===this._networkQualitySensitivity&&this.safeEmit(mT.NETWORK_QUALITY,e)})),this._gateway.on(XI.STREAM_TYPE_CHANGE,((e,t)=>{this.safeEmit(mT.STREAM_TYPE_CHANGED,e,t);eI.reportApiInvoke(this._sessionId,{name:hT.STREAM_TYPE_CHANGE,options:[e,t],tag:pT.TRACER}).onSuccess(JSON.stringify({uid:e,streamType:t}))})),this._gateway.on(XI.IS_P2P_DISCONNECTED,(e=>{this._p2pChannel.isP2PDisconnected()?e(!0):this._p2pChannel.hasLocalMedia()||this._p2pChannel.hasRemoteMedia()?e(!1):e(!0)})),this._gateway.on(XI.NEED_RENEW_SESSION,(()=>{this._startSession()})),this._gateway.on(XI.REQUEST_P2P_CONNECTION_PARAMS,(async(e,t,i)=>{try{t(await this._p2pChannel.startP2PConnection(e))}catch(e){i(e)}})),this._gateway.on(XI.JOIN_RESPONSE,((e,t)=>{if(this.store.useP2P)return;const{dtlsParameters:i,iceParameters:n,candidates:r,rtpCapabilities:s,setup:o,cname:a}=Rx(e.ortc,t);this._p2pChannel.connect(n,i,r,s,o,a)})),this._gateway.on(XI.REQUEST_DC_CONNECTION_PARAMS,(e=>{e(this._p2pChannel.getEstablishParams())})),this._gateway.on(XI.RESET_SIGNAL,(e=>{this._p2pChannel.resetConnection(e),this._handleGatewaySignalEvents()})),this._gateway.on(XI.DATACHANNEL_FAILBACK,(()=>{this._joinGateway()})),this._gateway.on(XI.DATACHANNEL_PRECONNECT,(async(e,t,i,n)=>{var r,s,o,a,c,d;await this._p2pChannel.startP2PConnection({turnServer:null===(r=this._joinInfo)||void 0===r?void 0:r.turnServer},!0);const l=function(e,t){let i;return t&&t.ip&&\"number\"==typeof t.port?(i=[{foundation:\"udpcandidate\",componentId:\"1\",transport:\"udp\",priority:\"2103266323\",connectionAddress:t.ip,port:t.port.toString(),type:\"host\",extension:{}}],jC.debug(\"Using remote candidate from AP \".concat(t.ip,\":\").concat(t.port)),t.ip6&&(i.push({foundation:\"udpcandidate\",componentId:\"1\",transport:\"udp\",priority:\"2103266323\",connectionAddress:t.ip6,port:t.port.toString(),type:\"host\",extension:{}}),jC.debug(\"Using IPV6 remote candidate from AP \".concat(t.ip6,\":\").concat(t.port)))):i=[{foundation:\"udpcandidate\",componentId:\"1\",transport:\"udp\",priority:\"2103266323\",connectionAddress:e.ip,port:e.port.toString(),type:\"host\",extension:{}}],i}(e,t);return this._p2pChannel.preConnect({iceUfrag:\"\".concat(null===(s=this._joinInfo)||void 0===s?void 0:s.apResponse.cid,\"_\").concat(null===(o=this._joinInfo)||void 0===o?void 0:o.apResponse.cert),icePwd:\"\".concat(null===(a=this._joinInfo)||void 0===a?void 0:a.apResponse.cid,\"_\").concat(null===(c=this._joinInfo)||void 0===c?void 0:c.apResponse.cert)},{fingerprints:[{hashFunction:\"sha-256\",fingerprint:null!==(d=RC(\"FINGERPRINT\"))&&void 0!==d?d:e.fingerprint}]},l,{send:{audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]},recv:{audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]}},\"active\",\"o/i14u9pJrxRKAsu\").then(i).catch(n)}))}_handleGatewaySignalEvents(){this._gateway.signal.on(fI.ON_USER_ONLINE,this._handleUserOnline),this._gateway.signal.on(fI.ON_USER_OFFLINE,this._handleUserOffline),this._gateway.signal.on(fI.ON_ADD_AUDIO_STREAM,(e=>this._handleAddAudioOrVideoStream(\"audio\",e.uid,e.ssrcId,e.cname,e.uint_id,e.ortc))),this._gateway.signal.on(fI.ON_ADD_VIDEO_STREAM,(e=>this._handleAddAudioOrVideoStream(\"video\",e.uid,e.ssrcId,e.cname,e.uint_id,e.ortc,e.rtxSsrcId))),this._gateway.signal.on(fI.ON_REMOTE_DATASTREAM_UPDATE,(e=>{this._handleUpdateDataChannel(e)})),this._gateway.signal.on(fI.ON_REMOTE_FULL_DATASTREAM_INFO,(e=>{this._handleUpdateDataChannel({added:e.datastreams,deleted:[]},!0)})),this._gateway.signal.on(fI.ON_REMOVE_STREAM,this._handleRemoveStream),this._gateway.signal.on(fI.ON_P2P_LOST,this._handleP2PLost),this._gateway.signal.on(fI.MUTE_AUDIO,(e=>this._handleMuteStream(e.uid,av.AUDIO,!0))),this._gateway.signal.on(fI.UNMUTE_AUDIO,(e=>this._handleMuteStream(e.uid,av.AUDIO,!1))),this._gateway.signal.on(fI.MUTE_VIDEO,(e=>this._handleMuteStream(e.uid,av.VIDEO,!0))),this._gateway.signal.on(fI.UNMUTE_VIDEO,(e=>this._handleMuteStream(e.uid,av.VIDEO,!1))),this._gateway.signal.on(fI.RECEIVE_METADATA,(e=>{const t=XT(e.metadata);this.safeEmit(mT.RECEIVE_METADATA,e.uid,t)})),this._gateway.signal.on(fI.ON_DATA_STREAM,(async e=>{var t;if(!e)return;let i=XT(e.payload);if(this._encryptDataStream&&this._encryptDataStreamIv&&this._encryptDataStreamKey&&window.crypto.subtle&&bn(t=[\"aes-128-gcm2\",\"aes-256-gcm2\"]).call(t,this._encryptionMode)){if(e.payload.lengtht.uid===e.uid)),r=null==t?void 0:t.audioRecv.find((e=>e.ssrc===(null==i?void 0:i._audioSSRC)));n=null==r?void 0:r.jitterBufferMs}null==n&&(n=0),bB(DB(DB({},e),{},{payload:i}),n,{id:this._clientId,onStreamMessage:\"function\"==typeof this.onStreamMessage?this.onStreamMessage.bind(this):void 0,safeEmit:this.safeEmit.bind(this)})})),this._gateway.signal.on(fI.ON_CRYPT_ERROR,(()=>{JT((()=>{jC.warning(\"[\".concat(this._clientId,\"] on crypt error\")),this.safeEmit(mT.CRYPT_ERROR)}),this._sessionId)})),this._gateway.signal.on(fI.ON_TOKEN_PRIVILEGE_WILL_EXPIRE,this._handleTokenWillExpire),this._gateway.signal.on(fI.ON_TOKEN_PRIVILEGE_DID_EXPIRE,(()=>{jC.warning(\"[\".concat(this._clientId,\"] received message onTokenPrivilegeDidExpire, please get new token and join again\")),this._gateway.leave(!0,ET.TOKEN_EXPIRE),this.safeEmit(mT.ON_TOKEN_PRIVILEGE_DID_EXPIRE),this._reset()})),this._gateway.signal.on(fI.ON_STREAM_FALLBACK_UPDATE,(e=>{jC.debug(\"[\".concat(this._clientId,\"] stream fallback peerId: \").concat(e.stream_id,\", attr: \").concat(e.stream_type)),this.safeEmit(mT.STREAM_FALLBACK,e.stream_id,1===e.stream_type?\"fallback\":\"recover\")})),this._gateway.signal.on(fI.ON_PUBLISH_STREAM,(e=>{this.uid===this._uid&&(this._p2pChannel.reportPublishEvent(!0,null,void 0,!1,JSON.stringify({proxy:e.proxy})),jC.info(\"[\".concat(this._clientId,\"] on publish stream, \").concat(JSON.stringify(e))))})),this._gateway.signal.on(fI.ENABLE_LOCAL_VIDEO,(e=>{this._handleSetStreamLocalEnable(\"video\",e.uid,!0)})),this._gateway.signal.on(fI.DISABLE_LOCAL_VIDEO,(e=>{this._handleSetStreamLocalEnable(\"video\",e.uid,!1)})),this._gateway.signal.on(_I.REQUEST_TIMEOUT,((e,t)=>{if(this._joinInfo)switch(e){case EI.PUBLISH:{if(!t)return;const e=t.ortc;if(e){var i,n;const r=e.some((e=>{let{stream_type:t}=e;return t===JI.Audio})),s=e.some((e=>{let{stream_type:t}=e;return t!==JI.Audio})),o=e.some((e=>{let{stream_type:t}=e;return t===JI.Screen||t===JI.ScreenLow}));\"offer\"===t.state&&eI.publish(this._joinInfo.sid,{eventElapse:RU.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:!1,ec:Hg.TIMEOUT,audio:r,video:s,p2pid:t.p2p_id,publishRequestid:this.store.pubId,screenshare:o,audioName:r?null===(i=e.find((e=>{let{stream_type:t}=e;return t===JI.Audio})))||void 0===i||null===(i=i.ssrcs[0])||void 0===i?void 0:i.ssrcId.toString():void 0,videoName:s?null===(n=e.find((e=>{let{stream_type:t}=e;return t!==JI.Audio})))||void 0===n||null===(n=n.ssrcs[0])||void 0===n?void 0:n.ssrcId.toString():void 0})}break}case EI.SUBSCRIBE:t&&eI.subscribe(this._joinInfo.sid,{succ:!1,ec:Hg.TIMEOUT,audio:t.stream_type===av.AUDIO,video:t.stream_type===av.VIDEO,peerid:t.stream_id,subscribeRequestid:t.ssrcId,p2pid:this.store.p2pId,eventElapse:RU.measureFromSubscribeStart(this.store.clientId,t.ssrcId)})}})),this._gateway.signal.on(fI.ON_P2P_OK,(e=>{this.uid,this._uid})),this._gateway.signal.on(fI.ON_PUBLISHED_USER_LIST,(e=>{if(null==e||!e.users)return;RC(\"BLOCK_LOCAL_CLIENT\")&&(e.users=e.users.filter((e=>!sI(e.string_id||e.stream_id,this.channelName))));const t=[],i=[];for(const n of e.users){let e=this._users.find((e=>e._uintid===n.stream_id));e?e._trust_in_room_=!0:(e=new sV(n.string_id||n.stream_id,n.stream_id),this._users.push(e),0===this.getListeners(mT.PUBLISHED_USER_LIST).length&&(jC.debug(\"[\".concat(this._clientId,\"] user online\"),n.stream_id),this.safeEmit(mT.USER_JOINED,e)));const r=ZI.Audio&n.stream_type,s=(ZI.Video|ZI.LwoVideo)&n.stream_type,o=0!=(65280&n.stream_type),a=r&&e.hasAudio,c=s&&e.hasVideo;s&&(e._trust_video_stream_added_state_=!0,e._video_added_=!0,e._videoSSRC=n.video_ssrc,e._rtxSsrcId=n.video_rtx),r&&(e._trust_audio_stream_added_state_=!0,e._audio_added_=!0,e._audioSSRC=n.audio_ssrc),r&&!a&&0===this.getListeners(mT.PUBLISHED_USER_LIST).length&&(jC.info(\"[\".concat(this._clientId,\"] remote user \").concat(e.uid,\" published audio\")),this.safeEmit(mT.USER_PUBLISHED,e,\"audio\")),s&&!c&&0===this.getListeners(mT.PUBLISHED_USER_LIST).length&&(jC.info(\"[\".concat(this._clientId,\"] remote user \").concat(e.uid,\" published video\")),this.safeEmit(mT.USER_PUBLISHED,e,\"video\")),(r&&!a||s&&!c||o)&&t.push(e),s&&this._p2pChannel.hasPendingRemoteMedia(e,\"video\")&&i.push({user:e,mediaType:\"video\"}),r&&this._p2pChannel.hasPendingRemoteMedia(e,\"audio\")&&i.push({user:e,mediaType:\"audio\"})}i.length>0&&(jC.debug(\"[\".concat(this._clientId,\"] RE massSubscribe after reconnect \").concat(i.map((e=>\"user: \".concat(e.user.uid,\", mediaType: \").concat(e.mediaType))).join(\"; \"),\" \")),this.massSubscribe(i).catch((e=>{jC.error(\"[\".concat(this._clientId,\"] mass resubscribe error\"),e.toString())}))),this.getListeners(mT.PUBLISHED_USER_LIST).length>0?RC(\"ENABLE_DATASTREAM_2\")?this._pendingPublishedUsers=t:(jC.info(\"[\".concat(this._clientId,\"] client emit user-list event, users: \").concat(t.map((e=>e.uid)).join(\", \"))),this.safeEmit(mT.PUBLISHED_USER_LIST,t)):jC.info(\"[\".concat(this._clientId,\"] client not emit user-list event case there is no user-list listener, users: \").concat(t.map((e=>e.uid)).join(\", \")))})),this._gateway.signal.on(fI.ON_RTP_CAPABILITY_CHANGE,(e=>{const{video_codec:t}=e;this._p2pChannel instanceof cF&&this._p2pChannel.updateRemoteRTPCapabilities(t.map((e=>e.toLowerCase())).filter((e=>{var t;return bn(t=Object.keys(bC)).call(t,e)})))}))}_handleP2PEvents(){this._gateway.signal.on(fI.ON_USER_OFFLINE,(()=>{this._p2pChannel.disconnectForReconnect()})),this._gateway.signal.on(vv.PUBLISH,((e,t,i)=>{const{uid:n}=e;e.forEach((e=>{const{kind:r,ssrcs:s,mid:o,isMuted:a}=e;this._handleP2PAddAudioOrVideoStream(r,n,s[0].ssrcId,o);const c=this._users.find((e=>e.uid===n));return c&&this._p2pChannel instanceof hV?this._p2pChannel.mockSubscribe(c,r,s[0].ssrcId,o).then((()=>{t()})).catch(i):t(),this._handleMuteStream(n,r,!!a)}))})),this._gateway.signal.on(vv.CALL,(async(e,t,i)=>{if(this._p2pChannel instanceof hV)try{var n;t(await this._p2pChannel.startP2P({turnServer:null===(n=this._joinInfo)||void 0===n?void 0:n.turnServer},e))}catch(e){i(e)}})),this._gateway.signal.on(_I.P2P_CONNECTION,(async e=>{this._p2pChannel instanceof hV&&await this._p2pChannel.p2pConnect(e)})),this._gateway.signal.on(vv.UNPUBLISH,(async(e,t,i)=>{if(this._p2pChannel instanceof hV){const{unpubMsg:n,uid:r}=e,s=this._users.find((e=>e.uid===r));if(!s)return jC.warning(\"[\".concat(this._clientId,\"] can not find remote user, ignore mute event, uid: \").concat(r)),void t();try{n.forEach((async e=>{let{stream_type:t}=e;const i=t===JI.Audio?av.AUDIO:av.VIDEO;await this._p2pChannel.unsubscribe(s,i),this._handleMuteStream(r,i,!0)})),t()}catch(e){i(e)}}})),this._gateway.signal.on(vv.CONTROL,(async(e,t)=>{const{action:i}=e;switch(i){case Av.MUTE_LOCAL_VIDEO:this._handleMuteStream(t,av.VIDEO,!0);break;case Av.MUTE_LOCAL_AUDIO:this._handleMuteStream(t,av.AUDIO,!0);break;case Av.UNMUTE_LOCAL_VIDEO:this._handleP2PAddAudioOrVideoStream(\"video\",t),this._handleMuteStream(t,av.VIDEO,!1);break;case Av.UNMUTE_LOCAL_AUDIO:this._handleP2PAddAudioOrVideoStream(\"audio\",t),this._handleMuteStream(t,av.AUDIO,!1)}})),this._gateway.signal.on(vv.RESTART_ICE,(async(e,t,i)=>{if(this._p2pChannel instanceof hV)try{const{direction:i,iceParameter:n}=e;if(i!==TI.SEND_ONLY||n){t(await this._p2pChannel.restartICE(i,n))}else this._p2pChannel.handleDisconnect(i),t()}catch(e){i(e)}})),this._gateway.signal.on(vv.CANDIDATE,(e=>{if(this._p2pChannel instanceof hV){const{candidate:t,direction:i}=e;this._p2pChannel.addRemoteCandidate(t,i)}})),this._p2pChannel.on(hv.RequestP2PRestartICE,(async(e,t,i)=>{try{const{direction:i}=e;t(await this._gateway.sendExtensionMessage(vv.RESTART_ICE,e,i===TI.SEND_ONLY))}catch(e){i(e)}})),this._p2pChannel.on(hv.LocalCandidate,(e=>{this._gateway.sendExtensionMessage(vv.CANDIDATE,JSON.stringify(e),!0)})),this._p2pChannel.on(hv.RequestP2PMuteLocal,(async(e,t,i)=>{try{await this._gateway.sendExtensionMessage(vv.CONTROL,e,!0),t()}catch(e){i(e)}})),this._p2pChannel.on(hv.RequestP2PUnmuteRemote,(async(e,t,i)=>{if(this._joinInfo)try{await this._gateway.unmuteRemote(e,this._joinInfo.stringUid||this._joinInfo.uid),t()}catch(e){e.code===Hg.DISCONNECT_P2P?t():i(e)}else t()})),this._p2pChannel.on(hv.RequestP2PMuteRemote,(async(e,t,i)=>{if(this._joinInfo)try{await this._gateway.muteRemote(e,this._joinInfo.stringUid||this._joinInfo.uid),t()}catch(e){e.code===Hg.DISCONNECT_P2P?t():i(e)}else t()})),this._p2pChannel.on(hv.StateChange,((e,t)=>{t===uv.Connected&&this._p2pChannel.republish()}))}_handleP2PChannelEvents(){this._p2pChannel.on(hv.RequestMuteLocal,(async(e,t,i)=>{if(this._joinInfo)try{await this._gateway.muteLocal(e,this._joinInfo.stringUid||this._joinInfo.uid),t()}catch(e){e.code===Hg.DISCONNECT_P2P?t():i(e)}else t()})),this._p2pChannel.on(hv.RequestUnmuteLocal,(async(e,t,i)=>{if(this._joinInfo)try{await this._gateway.unmuteLocal(e,this._joinInfo.stringUid||this._joinInfo.uid),t()}catch(e){e.code===Hg.DISCONNECT_P2P?t():i(e)}else t()})),this._p2pChannel.on(hv.RequestRePublish,((e,t,i)=>{this.publish(e,!1).then(t).catch(i)})),this._p2pChannel.on(hv.RequestRePublishDataChannel,((e,t,i)=>{cg.all(e.map((async e=>{await this._p2pChannel.publishDataChannel([e]);const t={streamId:e.id,ordered:e.ordered,maxRetransmits:e.maxRetransmits,metadata:e.metadata,channelId:e._originDataChannelId};try{await this._gateway.publishDataChannel(this._uid,t,!0)}catch(e){if(e.code!==Hg.DISCONNECT_P2P)throw e}}))).then(t).catch(i)})),this._p2pChannel.on(hv.RequestReSubscribe,(async(e,t,i)=>{try{for(const{user:t,kind:i}of e)i===av.VIDEO?await this.subscribe(t,\"video\"):await this.subscribe(t,\"audio\");t()}catch(e){i(e)}})),this._p2pChannel.on(hv.RequestUpload,((e,t)=>{this._gateway.upload(e,t)})),this._p2pChannel.on(hv.RequestUploadStats,(e=>{this._gateway.uploadWRTCStats(e)})),this._p2pChannel.on(hv.MediaReconnectStart,(e=>{this.safeEmit(mT.MEDIA_RECONNECT_START,e)})),this._p2pChannel.on(hv.MediaReconnectEnd,(e=>{this.safeEmit(mT.MEDIA_RECONNECT_END,e)})),this._p2pChannel.on(hv.NeedSignalRTT,(e=>{e(this._gateway.getSignalRTT())})),this._p2pChannel.on(hv.RequestRestartICE,(async e=>{if(this._p2pChannel instanceof hV)return;const t=await this._p2pChannel.restartICE(e),i=await t.next();if(i.done)return;const n=i.value;let r;try{r=await this._gateway.restartICE({iceParameters:n})}catch(e){return void t.throw(e)}const{iceParameters:s}=function(e){const t=e.iceParameters;return{iceParameters:{iceUfrag:t.iceUfrag,icePwd:t.icePwd}}}(r);await t.next({remoteIceParameters:s})})),this._p2pChannel.on(hv.RequestReconnect,(async()=>{this._gateway.reconnect()})),this._p2pChannel.on(hv.RequestReconnectPC,(async()=>{var e;const{iceParameters:t,dtlsParameters:i,rtpCapabilities:n}=await this._p2pChannel.startP2PConnection({turnServer:null===(e=this._joinInfo)||void 0===e?void 0:e.turnServer}),{gatewayEstablishParams:r,gatewayAddress:s}=await this._gateway.reconnectPC({iceParameters:t,dtlsParameters:i,rtpCapabilities:n}),{dtlsParameters:o,iceParameters:a,candidates:c,rtpCapabilities:d,setup:l,cname:u}=Rx(r,s);await this._p2pChannel.connect(a,o,c,d,l,u),await this._p2pChannel.republish(),await this._p2pChannel.reSubscribe()})),this._p2pChannel.on(hv.RequestUnpublishForReconnectPC,(async(e,t,i)=>{this._joinInfo&&void 0!==this._uid?(await this._gateway.unpublish(e,this._uid),t()):i()})),this._p2pChannel.on(hv.P2PLost,(()=>{this.safeEmit(mT.P2P_LOST,this.store.uid)})),this._p2pChannel.on(hv.UpdateVideoEncoder,(e=>{e._encoderConfig&&this._gateway.setVideoProfile(e._encoderConfig)})),this._p2pChannel.on(hv.ConnectionTypeChange,(e=>{this.safeEmit(mT.IS_USING_CLOUD_PROXY,e)})),this._p2pChannel.on(hv.RequestLowStreamParameter,(e=>{e(this._lowStreamParameter||{width:160,height:120,framerate:15,bitrate:50})})),this._p2pChannel.on(hv.QueryClientConnectionState,(e=>{e(this.connectionState)}))}getKeyMetrics(){return this.store.keyMetrics}async enableContentInspect(e){if(\"CONNECTED\"!==this.connectionState||!this._joinInfo)throw new LI(Hg.INVALID_OPERATION,\"[\".concat(this._clientId,\"] Client did not join channel\"));if(this._inspect)throw new LI(Hg.INVALID_OPERATION,\"[\".concat(this._clientId,\"] Inspect content service already in connecting/connected state\"));if(!e)throw new LI(Hg.INVALID_PARAMS,\"[\".concat(this._clientId,\"] inspectConfig is necessary\"));if(!e.inspectType||!Array.isArray(e.inspectType))throw new LI(Hg.INVALID_PARAMS,\"[\".concat(this._clientId,\"] inspectConfig.inspectType is necessary and is an instance of Array.\"));{const t=[...new Set(e.inspectType)];t.forEach((e=>{var t;if(!bn(t=[\"supervise\",\"moderation\"]).call(t,e))throw new LI(Hg.INVALID_PARAMS,\"[\".concat(this._clientId,\"] \").concat(e,\" is not a valid inspect type.\"))})),e.inspectType=t}if(e&&e.extraInfo&&e.extraInfo.length>1024)throw new LI(Hg.INVALID_PARAMS,\"[\".concat(this._clientId,\"] inspectConfig.extraInfo length cannot exceed 1024 bytes\"));try{const t=new FF(e);this._inspect=t,this.handleVideoInspectEvents(this._inspect),await t.init({appId:this._joinInfo.appId,areaCode:\"\",cname:this._joinInfo.cname,sid:this._joinInfo.sid,token:this._joinInfo.token,uid:this._joinInfo.uid,cid:this._joinInfo.cid,vid:this._joinInfo.vid?Number(this._joinInfo.vid):0},ES)}catch(e){throw Array.isArray(e)?e[0]:e}}async disableContentInspect(){if(!this._inspect)throw new LI(Hg.INVALID_OPERATION,\"[\".concat(this._clientId,\"] inspectVideoContent not started\"));try{this._inspect.close(),this._inspect=void 0}catch(e){throw Array.isArray(e)?e[0]:e}}async setImageModeration(e,t){if(Yg(e,\"enabled\"),e){if(!t)throw new LI(Hg.INVALID_PARAMS,\"[\".concat(this._clientId,\"] config is necessary\"));if(zg(t.interval,\"interval\",1e3,1/0),t&&t.extraInfo&&t.extraInfo.length>1024)throw new LI(Hg.INVALID_PARAMS,\"[\".concat(this._clientId,\"] config.extraInfo length cannot exceed 1024 bytes\"));if(t&&t.vendor&&t.vendor.length>1024)throw new LI(Hg.INVALID_PARAMS,\"[\".concat(this._clientId,\"] config.vendor length cannot exceed 1024 bytes\"));if(\"CONNECTED\"!==this.connectionState||!this._joinInfo)throw new LI(Hg.INVALID_OPERATION,\"[\".concat(this._clientId,'] can not enable image moderation, not joined\"'));try{if(this._moderation)return void this._moderation.updateConfig(t);const e=new gB(t);this._moderation=e,this.handleImageModerationEvents(this._moderation),await e.init({appId:this._joinInfo.appId,areaCode:\"\",cname:this._joinInfo.cname,sid:this._joinInfo.sid,token:this._joinInfo.token,uid:this._joinInfo.uid,cid:this._joinInfo.cid,vid:this._joinInfo.vid?Number(this._joinInfo.vid):0},ES)}catch(e){throw Array.isArray(e)?e[0]:e}}else{if(!this._moderation)throw new LI(Hg.INVALID_OPERATION,\"[\".concat(this._clientId,\"] image moderation not started\"));try{this._moderation.close(),this._moderation.removeAllListeners(),this._moderation=void 0}catch(e){throw Array.isArray(e)?e[0]:e}}}setP2PTransport(e){if(function(e){qg(e,\"transport\",[\"default\",\"auto\",\"relay\",\"sd-rtn\"])}(e),\"p2p\"!==this.mode)throw new LI(Hg.INVALID_OPERATION,\"only p2p mode can set p2pTransport\");this.store.p2pTransport=e,jC.info(\"[\".concat(this._clientId,\"] set client p2pTransport to \").concat(e))}handleImageModerationEvents(e){e.on(Cv.CONNECTION_STATE_CHANGE,((t,i)=>{if(this.safeEmit(mT.IMAGE_MODERATION_CONNECTION_STATE_CHANGE,t,i),t===Rv.CONNECTED){if(\"CONNECTED\"!==this.connectionState)throw this.setImageModeration(!1),new LI(Hg.OPERATION_ABORTED,\"Image moderation was cancelled because it left the channel\");e.inspectImage()}})),e.on(Cv.CLIENT_LOCAL_VIDEO_TRACK,(e=>{e(this.localTracks.filter((e=>\"video\"===e.trackMediaType))[0])}))}handleVideoInspectEvents(e){e.on(mv.CONNECTION_STATE_CHANGE,((t,i)=>{if(this.safeEmit(mT.CONTENT_INSPECT_CONNECTION_STATE_CHANGE,t,i),i===_v.CONNECTED){if(\"CONNECTED\"!==this.connectionState)return void this.safeEmit(mT.CONTENT_INSPECT_ERROR,new LI(Hg.OPERATION_ABORTED,\"Content inspect was cancelled because it left the channel\"));e.inspectImage()}})),e.on(mv.INSPECT_RESULT,((e,t)=>{var i;if((null==t?void 0:t.code)===Hg.INVALID_OPERATION&&\"DISCONNECTED\"===this.connectionState)return jC.debug(\"Stop inspect content because that has left channel\"),null==this||null===(i=this._inspect)||void 0===i||i.close(),void(this._inspect=void 0);this.safeEmit(mT.CONTENT_INSPECT_RESULT,e,t)})),e.on(mv.CLIENT_LOCAL_VIDEO_TRACK,(e=>{e(this.localTracks.filter((e=>\"video\"===e.trackMediaType))[0])}))}getJoinChannelServiceRecords(){return jC.debug(\"getJoinChannelServiceRecords\"),this.store.joinChannelServiceRecords}async setPublishAudioFilterEnabled(e){Yg(e,\"enabled\"),SC(\"ENABLE_PUBLISH_AUDIO_FILTER\",e),this._joinInfo&&await this._gateway.setPublishAudioFilterEnabled(e)}_handleResetAddStream(e,t){switch(t){case\"audio\":e._audio_added_=!1,e._trust_audio_stream_added_state_=!0;break;case\"video\":e._video_added_=!1,e._trust_video_stream_added_state_=!0}}}DI([$C(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[]),PI(\"design:returntype\",cg)],PB.prototype,\"leave\",null),DI([$C({argsMap:(e,t)=>{if(!Array.isArray(t)){if(!(t instanceof lb))return[t];t=[t]}return t.map((e=>e?Object(e).toString():\"null\"))}}),PI(\"design:type\",Function),PI(\"design:paramtypes\",[Object,Boolean]),PI(\"design:returntype\",cg)],PB.prototype,\"publish\",null),DI([$C({argsMap:(e,t)=>(t||(t=[]),t instanceof aP?[t.getChannelId()]:(Array.isArray(t)||(t=[t]),t.map((e=>e.getTrackId()))))}),PI(\"design:type\",Function),PI(\"design:paramtypes\",[Object]),PI(\"design:returntype\",cg)],PB.prototype,\"unpublish\",null),DI([$C({argsMap:(e,t,i,n)=>[t.uid,i,n]}),PI(\"design:type\",Function),PI(\"design:paramtypes\",[sV,String,Number]),PI(\"design:returntype\",cg)],PB.prototype,\"subscribe\",null),DI([$C({argsMap:(e,t,i)=>[t,i]}),PI(\"design:type\",Function),PI(\"design:paramtypes\",[Object,String]),PI(\"design:returntype\",cg)],PB.prototype,\"presubscribe\",null),DI([$C({argsMap:(e,t)=>t.map((e=>{let{user:t,mediaType:i}=e;return[null==t?void 0:t.uid,i]}))}),PI(\"design:type\",Function),PI(\"design:paramtypes\",[Array]),PI(\"design:returntype\",cg)],PB.prototype,\"massSubscribe\",null),DI([$C({argsMap:(e,t,i,n)=>[t.uid,i,n]}),PI(\"design:type\",Function),PI(\"design:paramtypes\",[sV,String,Number]),PI(\"design:returntype\",cg)],PB.prototype,\"unsubscribe\",null),DI([$C({argsMap:(e,t)=>t.map((e=>{let{user:t,mediaType:i}=e;return{uid:null==t?void 0:t.uid,mediaType:i}}))}),PI(\"design:type\",Function),PI(\"design:paramtypes\",[Array]),PI(\"design:returntype\",cg)],PB.prototype,\"massUnsubscribe\",null),DI([$C(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[Object]),PI(\"design:returntype\",cg)],PB.prototype,\"setLowStreamParameter\",null),DI([$C(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[]),PI(\"design:returntype\",cg)],PB.prototype,\"enableDualStream\",null),DI([$C(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[]),PI(\"design:returntype\",cg)],PB.prototype,\"disableDualStream\",null),DI([$C(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[String,Object]),PI(\"design:returntype\",cg)],PB.prototype,\"setClientRole\",null),DI([$C(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[String,Boolean]),PI(\"design:returntype\",void 0)],PB.prototype,\"setProxyServer\",null),DI([$C(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[Object,Boolean]),PI(\"design:returntype\",void 0)],PB.prototype,\"setTurnServer\",null),DI([$C(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[String]),PI(\"design:returntype\",void 0)],PB.prototype,\"setLicense\",null),DI([$C(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[Number]),PI(\"design:returntype\",void 0)],PB.prototype,\"startProxyServer\",null),DI([$C(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[]),PI(\"design:returntype\",void 0)],PB.prototype,\"stopProxyServer\",null),DI([$C(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[Object]),PI(\"design:returntype\",void 0)],PB.prototype,\"setLocalAccessPointsV2\",null),DI([$C(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[Array,String]),PI(\"design:returntype\",void 0)],PB.prototype,\"setLocalAccessPoints\",null),DI([$C(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[Number]),PI(\"design:returntype\",cg)],PB.prototype,\"setRemoteDefaultVideoStreamType\",null),DI([$C(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[Object,Number]),PI(\"design:returntype\",cg)],PB.prototype,\"setRemoteVideoStreamType\",null),DI([$C(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[Object,Number]),PI(\"design:returntype\",cg)],PB.prototype,\"setStreamFallbackOption\",null),DI([$C({argsMap:(e,t)=>[t]}),PI(\"design:type\",Function),PI(\"design:paramtypes\",[String,String,Uint8Array,Boolean]),PI(\"design:returntype\",void 0)],PB.prototype,\"setEncryptionConfig\",null),DI([$C(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[String]),PI(\"design:returntype\",cg)],PB.prototype,\"renewToken\",null),DI([$C(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[]),PI(\"design:returntype\",void 0)],PB.prototype,\"enableAudioVolumeIndicator\",null),DI([$C(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[String,Boolean]),PI(\"design:returntype\",cg)],PB.prototype,\"startLiveStreaming\",null),DI([$C(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[Object]),PI(\"design:returntype\",cg)],PB.prototype,\"setLiveTranscoding\",null),DI([$C(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[String]),PI(\"design:returntype\",cg)],PB.prototype,\"stopLiveStreaming\",null),DI([$C(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[String,Object]),PI(\"design:returntype\",cg)],PB.prototype,\"addInjectStreamUrl\",null),DI([$C(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[]),PI(\"design:returntype\",cg)],PB.prototype,\"removeInjectStreamUrl\",null),DI([$C(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[IV]),PI(\"design:returntype\",cg)],PB.prototype,\"startChannelMediaRelay\",null),DI([$C(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[IV]),PI(\"design:returntype\",cg)],PB.prototype,\"updateChannelMediaRelay\",null),DI([$C(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[]),PI(\"design:returntype\",cg)],PB.prototype,\"stopChannelMediaRelay\",null),DI([$C({argsMap:(e,t)=>(Array.isArray(t)||(t=[t]),[JSON.stringify(t)])}),PI(\"design:type\",Function),PI(\"design:paramtypes\",[Object]),PI(\"design:returntype\",cg)],PB.prototype,\"sendCustomReportMessage\",null),DI([$C(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[Object,Object]),PI(\"design:returntype\",cg)],PB.prototype,\"pickSVCLayer\",null),DI([$C(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[Object]),PI(\"design:returntype\",cg)],PB.prototype,\"setRTMConfig\",null),DI([$C(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[Object]),PI(\"design:returntype\",cg)],PB.prototype,\"enableContentInspect\",null),DI([$C(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[]),PI(\"design:returntype\",cg)],PB.prototype,\"disableContentInspect\",null),DI([$C(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[Boolean,Object]),PI(\"design:returntype\",cg)],PB.prototype,\"setImageModeration\",null),DI([$C(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[String]),PI(\"design:returntype\",void 0)],PB.prototype,\"setP2PTransport\",null),DI([$C({reportResult:!0}),PI(\"design:type\",Function),PI(\"design:paramtypes\",[]),PI(\"design:returntype\",Array)],PB.prototype,\"getJoinChannelServiceRecords\",null),DI([$C(),PI(\"design:type\",Function),PI(\"design:paramtypes\",[Boolean]),PI(\"design:returntype\",cg)],PB.prototype,\"setPublishAudioFilterEnabled\",null);class LB{constructor(e,t){sh(this,\"id\",0),sh(this,\"element\",void 0),sh(this,\"peerPair\",void 0),sh(this,\"context\",void 0),sh(this,\"audioPlayerElement\",void 0),sh(this,\"audioTrack\",void 0),LB.count+=1,this.id=LB.count,this.element=e,this.context=t}initPeers(){this.peerPair=[new RTCPeerConnection,new RTCPeerConnection],this.peerPair[1].ontrack=e=>{const t=document.createElement(\"audio\");t.srcObject=new MediaStream([e.track]),t.play(),this.audioPlayerElement=t}}async switchSdp(){if(!this.peerPair)return;const e=async(e,t)=>{const i=\"offer\"===t?await e.createOffer():await e.createAnswer();return await e.setLocalDescription(i),\"complete\"===e.iceGatheringState?e.localDescription:new cg((t=>{e.onicegatheringstatechange=()=>{\"complete\"===e.iceGatheringState&&t(e.localDescription)}}))},t=async(e,t)=>await e.setRemoteDescription(t);try{const i=await e(this.peerPair[0],\"offer\");await t(this.peerPair[1],i);const n=await e(this.peerPair[1],\"answer\");await t(this.peerPair[0],n)}catch(e){throw new LI(Hg.LOCAL_AEC_ERROR,e.toString()).print()}}async getTracksFromMediaElement(e){if(this.audioTrack)return this.audioTrack;let t;try{e instanceof HTMLVideoElement&&(e.captureStream?e.captureStream():e.mozCaptureStream()),t=this.context.createMediaStreamDestination();this.context.createMediaElementSource(e).connect(t)}catch(e){throw new LI(Hg.LOCAL_AEC_ERROR,e.toString()).print()}if(!t){throw new LI(Hg.LOCAL_AEC_ERROR,\"no dest node when local aec\").print()}const i=t.stream.getAudioTracks()[0];return this.audioTrack=i,i}getElement(){return this.element}async startEchoCancellation(){this.context.resume(),this.peerPair&&this.close(),this.initPeers();const e=this.element,t=await this.getTracksFromMediaElement(e);this.peerPair&&this.peerPair[0].addTrack(t),await this.switchSdp()}close(){jC.debug(\"close echo cancellation unit, id is\",this.id),this.audioPlayerElement&&this.audioPlayerElement.pause(),this.peerPair&&this.peerPair.forEach((e=>{e.close()})),this.peerPair=void 0,this.audioPlayerElement=void 0}}sh(LB,\"count\",0);const kB=window.AudioContext||window.webkitAudioContext;class MB{constructor(){sh(this,\"units\",[]),sh(this,\"context\",void 0)}processExternalMediaAEC(e){if(!this._doesEnvironmentNeedAEC())return jC.debug(\"the system does not need to process local aec\"),-1;this.context||(this.context=new kB);let t=this.units.find((t=>t&&t.getElement()===e));return t||(t=new LB(e,this.context),this.units.push(t)),t.startEchoCancellation(),jC.debug(\"start processing local audio echo cancellation, id is\",t.id),t.id}_doesEnvironmentNeedAEC(){return Sg().name!==Eg.SAFARI}}DI([$C({report:eI}),PI(\"design:type\",Function),PI(\"design:paramtypes\",[HTMLAudioElement]),PI(\"design:returntype\",Number)],MB.prototype,\"processExternalMediaAEC\",null);const UB=new MB;function xB(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function VB(e){for(var t=1;t1&&void 0!==arguments[1]&&arguments[1];if(!FB)return;const i=GB._cspEventHandlerPointer;if(i&&t)return void console.error(i,t);const n=e=>{if(!(e&&e.blockedURI&&(GB.onSecurityPolicyViolation||GB.getListeners(Tv.SECURITY_POLICY_VIOLATION).length>0)))return;const t=e.blockedURI;RC(\"CSP_DETECTED_HOSTNAME_LIST\").some((e=>bn(t).call(t,e)))&&(GB.onSecurityPolicyViolation&&\"function\"==typeof GB.onSecurityPolicyViolation&&GB.onSecurityPolicyViolation(e),GB.getListeners(Tv.SECURITY_POLICY_VIOLATION).length>0&&GB.safeEmit(Tv.SECURITY_POLICY_VIOLATION,e))};i&&FB.removeEventListener(\"securitypolicyviolation\",i),(t||e&&\"function\"==typeof e||GB.getListeners(Tv.SECURITY_POLICY_VIOLATION).length>0)&&FB.addEventListener(\"securitypolicyviolation\",n),GB._cspEventHandlerPointer=n}SC(\"PROCESS_ID\",\"process-\".concat(nS(8,\"\"),\"-\").concat(nS(4,\"\"),\"-\").concat(nS(4,\"\"),\"-\").concat(nS(4,\"\"),\"-\").concat(nS(12,\"\"))),function(){let e;try{e=window.localStorage.getItem(\"websdk_ng_global_parameter\")}catch(e){return void jC.error(\"Error loading sdk config\",e.message)}if(e)try{const t=JSON.parse(window.atob(e)),i=Date.now();jC.debug(\"Loading global parameters from cache\",t),Object.keys(t).forEach((e=>{if(Object.prototype.hasOwnProperty.call(TC,e)){const{value:n,expires:r}=t[e];if(r&&r<=i)return;CC[e]=n,TC[e]=n}}))}catch(t){jC.error(\"Error loading mutableParamsCache: \".concat(e),t.message)}}(),Array.isArray(CC.AREAS)&&CC.AREAS.length>0&&Jy(CC.AREAS,!0);const jB=(e,t,i)=>{jC.debug(\"setParameter key:\".concat(e,\", value:\").concat(JSON.stringify(t))),SC(e,t,i)},GB=function(e){const t=new dT,i=e,n={getListeners:t.getListeners.bind(t),on:(e,i)=>(function(e,t){e===Tv.SECURITY_POLICY_VIOLATION&&BB(t,!0)}(e,i),t.on.bind(t)(e,i)),addListener:t.addListener.bind(t),once:t.once.bind(t),off:t.off.bind(t),removeAllListeners:t.removeAllListeners.bind(t),emit:t.emit.bind(t),safeEmit:t.safeEmit.bind(t)};return VB(VB({},i),n)}({__TRACK_LIST__:VA,VERSION:EC,BUILD:gC,ESM_BUNDLER:!1,ESM:!1,UMD:!0,DEV:!1,setParameter:jB,getParameter:RC,getSupportedCodec:async function(){let e={audio:[],video:[]};try{let t=new RTCPeerConnection;t.addTransceiver(\"video\",{direction:\"recvonly\"}),t.addTransceiver(\"audio\",{direction:\"recvonly\"});const i=(await t.createOffer()).sdp;if(!i)return e;t.close(),t=null,e=function(e){const t={video:[],audio:[]};return e.match(/ VP8/i)&&t.video.push(\"VP8\"),e.match(/ VP9/i)&&t.video.push(\"VP9\"),e.match(/ AV1/i)&&t.video.push(\"AV1\"),e.match(/ H264/i)&&t.video.push(\"H264\"),e.match(/ H265/i)&&t.video.push(\"H265\"),e.match(/ opus/i)&&t.audio.push(\"OPUS\"),e.match(/ PCMU/i)&&t.audio.push(\"PCMU\"),e.match(/ PCMA/i)&&t.audio.push(\"PCMA\"),e.match(/ G722/i)&&t.audio.push(\"G722\"),t}(i)}catch(e){throw new LI(Hg.CREATE_OFFER_FAILED,e.toString&&e.toString()).print()}return e},checkSystemRequirements:function(){const e=eI.reportApiInvoke(null,{name:hT.CHECK_SYSTEM_REQUIREMENTS,options:[],tag:pT.TRACER});let t=!1;try{const e=window.RTCPeerConnection,i=navigator.mediaDevices&&navigator.mediaDevices.getUserMedia,n=window.WebSocket;t=!!(e&&i&&n)}catch(e){return jC.error(\"check system requirement failed: \",e),!1}let i=!1;const n=Sg();n.name===Eg.CHROME&&Number(n.version)>=58&&(!yg()||vg())&&(i=!0),n.name===Eg.FIREFOX&&Number(n.version)>=56&&(i=!0),n.name===Eg.OPERA&&Number(n.version)>=45&&(i=!0),n.name===Eg.SAFARI&&Number(n.version)>=11&&(i=!0),(Fg()||Sg().name===Eg.QQ)&&(i=!0),jC.debug(\"checkSystemRequirements, api:\",t,\"browser\",i);const r=t&&i;return e.onSuccess(r),r},getDevices:function(e){return kb.enumerateDevices(!0,!0,e)},getMicrophones:function(e){return kb.getRecordingDevices(e)},getCameras:function(e){return kb.getCamerasDevices(e)},getElectronScreenSources:yb,getPlaybackDevices:function(e){return kb.getSpeakers(e)},createClient:function(){var e;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{codec:\"vp8\",audioCodec:\"opus\",mode:\"rtc\"};const i=eI.reportApiInvoke(null,{name:hT.CREATE_CLIENT,options:[t],tag:pT.TRACER});try{!function(e){qg(e.codec,\"config.codec\",[\"vp8\",\"vp9\",\"av1\",\"h264\",\"h265\"]),qg(e.mode,\"config.mode\",[\"rtc\",\"live\",\"p2p\"]),void 0!==e.audioCodec&&qg(e.audioCodec,\"config.audioCodec\",[\"opus\",\"pcmu\",\"pcma\",\"g722\"]),void 0!==e.proxyServer&&Xg(e.proxyServer,\"config.proxyServer\",1,1e4),void 0!==e.turnServer&&CT(e.turnServer),void 0!==e.httpRetryConfig&&ST(e.httpRetryConfig),void 0!==e.websocketRetryConfig&&ST(e.websocketRetryConfig)}(t)}catch(e){throw i.onError(e),e}return OB()||(\"vp9\"===t.codec&&(t.codec=\"vp8\",jC.debug(\"browser not support vp9, force use vp8\")),SC(\"UNSUPPORTED_VIDEO_CODEC\",[\"vp9\"])),void 0===t.audioCodec&&(t.audioCodec=\"opus\"),i.onSuccess(),new PB(DB(DB({forceWaitGatewayResponse:!0},t),{},{role:bn(e=[\"rtc\",\"p2p\"]).call(e,t.mode)?\"host\":t.role||\"audience\"}))},createCameraVideoTrack:async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const t=eI.reportApiInvoke(null,{tag:pT.TRACER,name:hT.CREATE_CAM_VIDEO_TRACK,options:[vw({},e)]}),i=rw(e),n=nS(8,\"track-cam-\");let r=null;const s=\"720p_auto\"===e.encoderConfig;jC.info(\"start create camera video track with config\",JSON.stringify(e),\"trackId\",n);try{r=(await Nb({video:i},n)).getVideoTracks()[0]||null}catch(e){throw t.onError(e),e}if(!r){const e=new Kg(Hg.UNEXPECTED_ERROR,\"can not find track in media stream\");return t.onError(e),e.throw(jC)}e.optimizationMode&&yw(n,r,e,LA(e.encoderConfig));const o=new Cw(r,e,i,e.scalabiltyMode?MA(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,n);return s&&o.startMonitorStats(),t.onSuccess(o.getTrackId()),jC.info(\"create camera video success, trackId:\",n),o},createCustomVideoTrack:function(e){const t=eI.reportApiInvoke(null,{tag:pT.TRACER,name:hT.CREATE_CUSTOM_VIDEO_TRACK,options:[e]}),i=new Rw(e.mediaStreamTrack,{width:e.width,height:e.height,frameRate:e.frameRate,bitrateMax:e.bitrateMax,bitrateMin:e.bitrateMin},e.scalabiltyMode?MA(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,nS(8,\"track-cus-\"),[jA.CUSTOM_TRACK]);return t.onSuccess(i.getTrackId()),jC.info(\"create custom video track success with config\",e,\"trackId\",i.getTrackId()),i},createScreenVideoTrack:async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:\"disable\";const i=eI.reportApiInvoke(null,{tag:pT.TRACER,name:hT.CREATE_SCREEN_VIDEO_TRACK,options:[vw({},e),t]}),n=\"720p_auto\"===e.encoderConfig;e.encoderConfig?\"string\"==typeof e.encoderConfig||e.encoderConfig.width&&e.encoderConfig.height||(e.encoderConfig.width={max:1920},e.encoderConfig.height={max:1080}):e.encoderConfig=\"1080p_2\";const r=function(e){const t={};e.screenSourceType&&(t.mediaSource=e.screenSourceType),e.extensionId&&Ag()&&(t.extensionId=e.extensionId);const{displaySurface:i,selfBrowserSurface:n,surfaceSwitching:r,systemAudio:s}=e;(Ng(107)||Dg(107)||Pg(93))&&(i&&(qg(i,\"displaySurface\",[\"browser\",\"window\",\"monitor\"]),t.displaySurface=i),n?(qg(n,\"selfBrowserSurface\",[\"exclude\",\"include\"]),t.selfBrowserSurface=n):t.selfBrowserSurface=\"include\",r&&(qg(r,\"surfaceSwitching\",[\"exclude\",\"include\"]),t.surfaceSwitching=r)),(Ng(105)||Dg(105)||Pg(91))&&s&&(qg(s,\"systemAudio\",[\"exclude\",\"include\"]),t.systemAudio=s),e.electronScreenSourceId&&(t.sourceId=e.electronScreenSourceId);const o=e.encoderConfig?kA(e.encoderConfig):null;return t.mandatory={chromeMediaSource:\"desktop\",maxWidth:o?o.width:void 0,maxHeight:o?o.height:void 0},o&&(o.frameRate&&(\"number\"==typeof o.frameRate?(t.mandatory.maxFrameRate=o.frameRate,t.mandatory.minFrameRate=o.frameRate):(t.mandatory.maxFrameRate=o.frameRate.max||o.frameRate.ideal||o.frameRate.exact||void 0,t.mandatory.minFrameRate=o.frameRate.min||o.frameRate.ideal||o.frameRate.exact||void 0),t.frameRate=o.frameRate),o.width&&(t.width=o.width),o.height&&(t.height=o.height)),t}(e),s=nS(8,\"track-scr-v-\");let o=null,a=null;const c=IA();if(!c.supportShareAudio&&\"enable\"===t){const e=new Kg(Hg.NOT_SUPPORTED,\"your browser or platform is not support share-screen with audio\");return i.onError(e),e.throw(jC)}jC.info(\"start create screen video track with config\",e,\"withAudio\",t,\"trackId\",s);try{const e=await Nb({screen:r,screenAudio:\"auto\"===t?c.supportShareAudio:\"enable\"===t},s);o=e.getVideoTracks()[0]||null,a=e.getAudioTracks()[0]||null}catch(e){throw i.onError(e),e}if(!o){const e=new Kg(Hg.UNEXPECTED_ERROR,\"can not find track in media stream\");return i.onError(e),e.throw(jC)}if(!a&&\"enable\"===t){o&&o.stop();const e=new Kg(Hg.SHARE_AUDIO_NOT_ALLOWED);return i.onError(e),e.throw(jC)}if(e.optimizationMode||(e.optimizationMode=\"detail\"),e.optimizationMode){yw(s,o,e,e.encoderConfig&&kA(e.encoderConfig)||void 0),e.encoderConfig&&\"string\"!=typeof e.encoderConfig&&(e.encoderConfig.bitrateMin=e.encoderConfig.bitrateMax)}const d=new Rw(o,e.encoderConfig?kA(e.encoderConfig):{},e.scalabiltyMode?MA(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,s,[jA.SCREEN_TRACK]);if(n&&d.startMonitorStats(),!a)return i.onSuccess(d.getTrackId()),jC.info(\"create screen video track success\",\"video:\",d.getTrackId()),d;const l=new ew(a,void 0,nS(8,\"track-scr-a-\"),!1);return i.onSuccess([d.getTrackId(),l.getTrackId()]),jC.info(\"create screen video track success\",\"video:\",d.getTrackId(),\"audio:\",l.getTrackId()),[d,l]},createMicrophoneAndCameraTracks:async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i=eI.reportApiInvoke(null,{tag:pT.TRACER,name:hT.CREATE_MIC_AND_CAM_TRACKS,options:[e,t]}),n=\"720p_auto\"===t.encoderConfig,r=rw(t),s=sw(e),o=nS(8,\"track-mic-\"),a=nS(8,\"track-cam-\");let c=null,d=null;jC.info(\"start create camera video track(\".concat(a,\") and microphone audio track(\").concat(o,\") with config, audio: \").concat(JSON.stringify(e),\", video: \").concat(JSON.stringify(t)));try{const e=await Nb({audio:s,video:r},\"\".concat(o,\"-\").concat(a));c=e.getAudioTracks()[0],d=e.getVideoTracks()[0]}catch(e){throw i.onError(e),e}if(!c||!d){const e=new Kg(Hg.UNEXPECTED_ERROR,\"can not find tracks in media stream\");return i.onError(e),e.throw(jC)}t.optimizationMode&&yw(a,d,t,LA(t.encoderConfig));const l=new tw(c,e,s,o),u=new Cw(d,t,r,t.scalabiltyMode?MA(t.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},t.optimizationMode,a);return n&&u.startMonitorStats(),i.onSuccess([l.getTrackId(),u.getTrackId()]),jC.info(\"create camera video track(\".concat(a,\") and microphone audio track(\").concat(o,\") success\")),[l,u]},createMicrophoneAudioTrack:async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const t=eI.reportApiInvoke(null,{tag:pT.TRACER,name:hT.CREATE_MIC_AUDIO_TRACK,options:[e]}),i=sw(e),n=nS(8,\"track-mic-\");let r=null;jC.info(\"start create microphone audio track with config\",JSON.stringify(e),\"trackId\",n);try{r=(await Nb({audio:i},n)).getAudioTracks()[0]||null}catch(e){throw t.onError(e),e}if(!r){const e=new Kg(Hg.UNEXPECTED_ERROR,\"can not find track in media stream\");return t.onError(e),e.throw(jC)}const s=new tw(r,e,i,n);return t.onSuccess(s.getTrackId()),jC.info(\"create microphone audio track success, trackId:\",n),s},createCustomAudioTrack:function(e){const t=eI.reportApiInvoke(null,{tag:pT.TRACER,name:hT.CREATE_CUSTOM_AUDIO_TRACK,options:[e]}),i=new ew(e.mediaStreamTrack,e.encoderConfig?xA(e.encoderConfig):{},nS(8,\"track-cus-\"),!1);return jC.info(\"create custom audio track success with config\",e,\"trackId\",i.getTrackId()),t.onSuccess(i.getTrackId()),i},createBufferSourceAudioTrack:async function(e){var t;const{cacheOnlineFile:i,encoderConfig:n}=e;let{source:r}=e;const s={source:r instanceof AudioBuffer?\"AudioBuffer\":r instanceof File?null!==(t=File.name)&&void 0!==t?t:\"File\":r,cacheOnlineFile:i,encoderConfig:n},o=eI.reportApiInvoke(null,{tag:pT.TRACER,name:hT.CREATE_BUFFER_AUDIO_TRACK,options:[s]});if(RC(\"DISABLE_WEBAUDIO\"))throw new Kg(Hg.NOT_SUPPORTED,\"can not create BufferSourceAudioTrack when WebAudio disabled\");const a=nS(8,\"track-buf-\");jC.info(\"start create buffer source audio track with config\",JSON.stringify(s),\"trackId\",a);const c=r;if(!(r instanceof AudioBuffer))try{r=await cw(r,i)}catch(e){return o.onError(e),e.throw(jC)}const d=new ow(r),l=new iw(c,d,n?xA(n):{},a);return jC.info(\"create buffer source audio track success, trackId:\",a),o.onSuccess(l.getTrackId()),l},setAppType:function(e){if(jC.debug(\"setAppType: \".concat(e)),!(Number.isInteger(e)&&e>=0))throw jC.debug(\"Invalid appType\"),new LI(Hg.INVALID_PARAMS,\"invalid app type\",e);SC(\"APP_TYPE\",Math.floor(e))},setLogLevel:function(e){jC.setLogLevel(e)},enableLogUpload:function(){RC(\"USE_NEW_LOG\")?SC(\"UPLOAD_LOG\",!0):jC.enableLogUpload()},disableLogUpload:function(){RC(\"USE_NEW_LOG\")?SC(\"UPLOAD_LOG\",!1):jC.disableLogUpload()},createChannelMediaRelayConfiguration:function(){return new IV},checkAudioTrackIsActive:async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;const i=eI.reportApiInvoke(null,{tag:pT.TRACER,name:hT.CHECK_AUDIO_TRACK_IS_ACTIVE,options:[t]});if(!(e instanceof ew||e instanceof Nw)){const e=new LI(Hg.INVALID_TRACK,\"the parameter is not a audio track\");return i.onError(e),e.throw()}t&&t<1e3&&(t=1e3);const n=e instanceof ew?e.getTrackLabel():\"remote_track\",r=e.getVolumeLevel();let s=r,o=r;const a=Date.now();return new cg((r=>{const c=setInterval((()=>{const d=e.getVolumeLevel();s=d>s?d:s,o=d1e-4,u=Date.now()-a;if(l||u>t){clearInterval(c);const t=l,o={duration:u,deviceLabel:n,maxVolumeLevel:s,result:t};jC.info(\"[track-\".concat(e.getTrackId(),\"] check audio track active completed. \").concat(JSON.stringify(o))),i.onSuccess(o),r(t)}}),200)}))},checkVideoTrackIsActive:async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;const i=eI.reportApiInvoke(null,{tag:pT.TRACER,name:hT.CHECK_VIDEO_TRACK_IS_ACTIVE,options:[t]});if(!(e instanceof Rw||e instanceof Ow)){const e=new LI(Hg.INVALID_TRACK,\"the parameter is not a video track\");return i.onError(e),e.throw()}t&&t<1e3&&(t=1e3);const n=e instanceof Rw?e.getTrackLabel():\"remote_track\",r=e.getMediaStreamTrack(!0),s=document.createElement(\"video\");s.style.width=\"1px\",s.style.height=\"1px\",s.setAttribute(\"muted\",\"\"),s.muted=!0,s.setAttribute(\"playsinline\",\"\"),s.controls=!1,(bg()||Ig())&&(s.style.opacity=\"0.01\",s.style.position=\"fixed\",s.style.left=\"0\",s.style.top=\"0\",document.body.appendChild(s)),s.srcObject=new MediaStream([r]),s.play();const o=document.createElement(\"canvas\");o.width=160,o.height=120;let a=0,c=0;try{const e=Date.now();a=await function(e,t,i,n){let r,s=0,o=null;return new cg(((a,c)=>{function d(){s>n&&r&&(r(),a(s));const t=i.getContext(\"2d\");if(!t){const e=new LI(Hg.UNEXPECTED_ERROR,\"can not get canvas 2d context.\");return jC.error(e.toString()),void c(e)}t.drawImage(e,0,0,160,120);const d=t.getImageData(0,0,i.width,i.height),l=Math.floor(d.data.length/3);if(o){for(let e=0;e{r&&(r(),a(s))}),t),r=Tb((()=>{d()}),30)}))}(s,t,o,4),c=Date.now()-e}catch(e){throw i.onError(e),e}wB===Eg.SAFARI&&(s.pause(),s.remove()),s.srcObject=null;const d=a>4,l={duration:c,changedPicNum:a,deviceLabel:n,result:d};return jC.info(\"[track-\".concat(e.getTrackId(),\"] check video track active completed. \").concat(JSON.stringify(l))),i.onSuccess(l),d},setArea:Jy,audioElementPlayCenter:Gb,resumeAudioContext:function(){Gb.autoResumeAfterInterruption(!0)},processExternalMediaAEC:function(e){UB.processExternalMediaAEC(e)},registerExtensions:function(e){const t=RC(\"PLUGIN_INFO\")||[];e.forEach((e=>{\"name\"in e&&!bn(t).call(t,e.name)&&t.push(e.name);const i=e;i.__registered__=!0,i.logger.hookLog=jC.extLog,i.reporter.hookApiInvoke=eI.extApiInvoke,i.parameters&&Object.keys(i.parameters).forEach((e=>{i.parameters[e]=RC(e)}))})),jB(\"PLUGIN_INFO\",t)},ChannelMediaRelayError:zI,ChannelMediaRelayEvent:YI,ChannelMediaRelayState:qI,RemoteStreamFallbackType:HA,RemoteStreamType:WA,ConnectionDisconnectedReason:ET,AudienceLatencyLevelType:_T,AREAS:ev});return Object.defineProperties(GB,{onAudioAutoplayFailed:{get:()=>Ub.onAudioAutoplayFailed,set:e=>{Ub.onAudioAutoplayFailed=e}},onAutoplayFailed:{get:()=>Ub.onAutoplayFailed,set:e=>{Ub.onAutoplayFailed=e}},_onSecurityPolicyViolation:{value:void 0,writable:!0},_cspEventHandlerPointer:{value:void 0,writable:!0},onSecurityPolicyViolation:{get:()=>GB._onSecurityPolicyViolation,set(e){GB._onSecurityPolicyViolation=e,BB(e)}},__CLIENT_LIST__:{get:()=>RC(\"SHOW_GLOBAL_CLIENT_LIST\")?rI:[]}}),kb.on(rb.CAMERA_DEVICE_CHANGED,(e=>{jC.info(\"camera device changed\",JSON.stringify(e)),GB.onCameraChanged&&GB.onCameraChanged(e),GB.safeEmit(Tv.CAMERA_CHANGED,e)})),kb.on(rb.RECORDING_DEVICE_CHANGED,(e=>{jC.info(\"microphone device changed\",JSON.stringify(e)),GB.onMicrophoneChanged&&GB.onMicrophoneChanged(e),GB.safeEmit(Tv.MICROPHONE_CHANGED,e)})),kb.on(rb.PLAYOUT_DEVICE_CHANGED,(e=>{jC.debug(\"playout device changed\",JSON.stringify(e)),GB.onPlaybackDeviceChanged&&GB.onPlaybackDeviceChanged(e),GB.safeEmit(Tv.PLAYBACK_DEVICE_CHANGED,e)})),Gb.onAutoplayFailed=()=>{jC.info(\"detect audio element autoplay failed\"),Ub.onAudioAutoplayFailed&&Ub.onAudioAutoplayFailed()},_b.on(\"autoplay-failed\",(()=>{jC.info(\"detect webaudio autoplay failed\"),Ub.onAudioAutoplayFailed&&Ub.onAudioAutoplayFailed(),GB.safeEmit(Tv.AUTOPLAY_FAILED)})),_b.on(vA.STATE_CHANGE,((e,t)=>{jC.info(\"audio context state changed: \".concat(t,\" => \").concat(e)),GB.onAudioContextStateChanged&&GB.onAudioContextStateChanged(e,t),GB.safeEmit(Tv.AUDIO_CONTEXT_STATE_CHANGED,e,t)})),wT.on(TT.NETWORK_STATE_CHANGE,((e,t)=>{jC.info(\"[network-indicator] network state changed, \".concat(t,\" => \").concat(e))})),window&&(window.__ARTC__=GB),GB}));\n", "import AgoraRTC, {\n ClientRole,\n ConnectionDisconnectedReason,\n ConnectionState,\n IAgoraRTCClient,\n IAgoraRTCRemoteUser,\n ICameraVideoTrack,\n IMicrophoneAudioTrack,\n IRemoteAudioTrack,\n IRemoteVideoTrack,\n NetworkQuality,\n UID,\n VideoEncoderConfiguration\n} from \"agora-rtc-sdk-ng\";\nimport {\n MediaStreamingHostsUpdateType,\n ParticipantRolesEnum,\n WebcastAuctionConnectData_TypeDef, WebcastAuctionHandler\n} from \"@nextlot/core/webcast/services/AuctionsManager\";\nimport {TaggedLogger} from \"@nextlot/core/utilities\";\n\n\n// https://docs.agora.io/en/Interactive%20Broadcast/start_live_web_ng?platform=Web\n// https://docs.agora.io/en/Interactive%20Broadcast/API%20Reference/web_ng/v4.13.0/index.html\n\n\nconst AgoraLogLevels = {\n DEBUG: 0, //Output all API logs.\n INFO: 1, // Output logs of the INFO, WARNING and ERROR level.\n WARNING: 2, // Output logs of the WARNING and ERROR level.\n ERROR: 3, // Output logs of the ERROR level.\n NONE: 4, // Do not output any log.\n}\n\nAgoraRTC.setLogLevel(__DEV__ ? AgoraLogLevels.WARNING : AgoraLogLevels.INFO);\n// AgoraRTC.enableLogUpload();\n\n\n\nexport enum ConnectStatusIdEnum {\n not_connected = 0,\n connecting = 3,\n connected_ok = 9,\n connect_error = -9\n}\n\n\nexport type StreamQualitySettingsType = {\n audioProfileCode:string,\n videoProfileCode:string,\n}\n\nexport type MasterRemoteUsersTypeDef = {\n audioRemoteUser?:IAgoraRTCRemoteUser|false|true,\n videoRemoteUser?:IAgoraRTCRemoteUser|false|true,\n}\n\n\n\n\nexport const MEDIA_QUALITY_VIDEO_PROFILES_CODES_MAP:{ [key: string]: VideoEncoderConfiguration } = {\n '160_120_7': { bitrateMin: 60*1024, bitrateMax: 140*1024, frameRate: { min: 5, max: 7 }, width: 160, height: 120 },\n '160_120_15': { bitrateMin: 100*1024, bitrateMax: 200*1024, frameRate: { min: 11, max: 15 }, width: 160, height: 120 },\n\n '320_240_2': { bitrateMin: 100*1024, bitrateMax: 200*1024, frameRate: { min: 2, max: 3 }, width: 320, height: 240 },\n '320_240_7': { bitrateMin: 100*1024, bitrateMax: 200*1024, frameRate: { min: 5, max: 7 }, width: 320, height: 240 },\n '320_240_15': { bitrateMin: 180*1024, bitrateMax: 250*1024, frameRate: { min: 14, max: 16 }, width: 320, height: 240 },\n\n '640_480_2': { bitrateMin: 150*1024, bitrateMax: 250*1024, frameRate: { min: 2, max: 3 }, width: 640, height: 480 },\n '640_480_7': { bitrateMin: 350*1024, bitrateMax: 450*1024, frameRate: { min: 5, max: 8 }, width: 640, height: 480 },\n '640_480_15': { bitrateMin: 450*1024, bitrateMax: 550*1024, frameRate: { min: 14, max: 16 }, width: 640, height: 480 },\n '640_480_30': { bitrateMin: 700*1024, bitrateMax: 1000*1024, frameRate: { min: 25, max: 30 }, width: 640, height: 480 },\n\n '1280_720_7': { bitrateMin: 1000*1024, bitrateMax: 1200*1024, frameRate: { min: 5, max: 7 }, width: 1280, height: 720 },\n '1280_720_15': { bitrateMin: 1100*1024, bitrateMax: 1500*1024, frameRate: { min: 11, max: 15 }, width: 1280, height: 720 },\n};\n\n\n\nexport const MEDIA_QUALITY_AUDIO_PROFILES_CODES_MAP = {\n 'low': 'speech_low_quality',\n 'med': 'speech_standard',\n 'standard': 'music_standard',\n 'high': 'high_quality',\n};\n\n\nenum AgoraMediaTypeEnum {\n video = \"video\",\n audio = \"audio\"\n}\n\ntype StreamingConnectDataTypeDef = Pick\n\n\n\n/**\n * private abstract base class for Publisher and Subscriber\n */\nclass AbstractAgoraService {\n protected _logger:TaggedLogger;\n\n protected readonly agoraAppId:string;\n public readonly agoraChannelName:string;\n protected readonly agoraToken:string;\n protected readonly rtcClientRole:ClientRole;\n protected readonly rtcClient:IAgoraRTCClient;\n protected readonly webcastAuctionHandler:WebcastAuctionHandler;\n\n public myAgoraUid:UID;\n\n protected wbsAudioUid:UID;\n protected wbsVideoUid:UID;\n\n protected availableAudioRemoteUsers:Map;\n protected availableVideoRemoteUsers:Map;\n\n protected currentMasterRemoteUsers:MasterRemoteUsersTypeDef;\n // protected currentMasterAudioRemoteUser:IAgoraRTCRemoteUser|false|true;\n // protected currentMasterVideoRemoteUser:IAgoraRTCRemoteUser|false|true;\n\n private unsubscribeMediaHostUpdateListener:()=>void;\n private listener_remoteMasterStreamsChanged:(change:MasterRemoteUsersTypeDef)=>void;\n\n\n\n constructor(webcastAuctionHandler:WebcastAuctionHandler) {\n this._logger = TaggedLogger.get(this.constructor.name);\n\n this._logger.info('.constructor() ', webcastAuctionHandler);\n\n this.webcastAuctionHandler = webcastAuctionHandler;\n this.agoraAppId = webcastAuctionHandler.auctionConnectData.streamingAgoraAppId;\n this.agoraChannelName = webcastAuctionHandler.auctionConnectData.streamingAgoraChannelName;\n this.agoraToken = webcastAuctionHandler.auctionConnectData.streamingAgoraToken;\n\n this.rtcClientRole = webcastAuctionHandler.auctionConnectData.participantRole === ParticipantRolesEnum.clerk\n ? 'host'\n : 'audience';\n\n this.availableAudioRemoteUsers = new Map();\n this.availableVideoRemoteUsers = new Map();\n this.currentMasterRemoteUsers = {};\n\n this.rtcClient = AgoraRTC.createClient({ mode: \"live\", codec: \"h264\", role: this.rtcClientRole });\n\n (window as any)._dev_agoraRtcClient = this.rtcClient; // DEBUG\n }\n\n\n _registerListeners() {\n this.rtcClient.on('connection-state-change', (curState: ConnectionState, prevState: ConnectionState, reason?: ConnectionDisconnectedReason) => {\n this._logger.debug(`.rtcClient>>[connection-state-change]: `, prevState, '->', curState, ' reason:',reason);\n });\n\n this.rtcClient.on('network-quality', (stats: NetworkQuality) => {\n // this._logger.debug(`.rtcClient>>[network-quality]: `, stats);\n });\n\n this.rtcClient.on('exception', (event) => {\n this._logger.error(`.rtcClient>>[exception]: `, event);\n });\n\n this.rtcClient.on('token-privilege-will-expire', () => {\n this._logger.warn(`.rtcClient>>[token-privilege-will-expire]: `);\n });\n\n // this.rtcClient.on('user-joined', (user: IAgoraRTCRemoteUser) => {\n // this._logger.debug(`.rtcClient>>[user-joined]: user:`, user);\n // });\n //\n // this.rtcClient.on('user-left', (user: IAgoraRTCRemoteUser, reason) => {\n // this._logger.debug(`.rtcClient>>[user-left]: user:`, user, ' reason:', reason);\n // });\n\n\n\n this.rtcClient.on('user-published', (user: IAgoraRTCRemoteUser, mediaType) => {\n // this._logger.debug(`.rtcClient>>[user-published]: mediaType:`, mediaType, ' user:', user);\n this._handleRemoteTrackAdded(user, mediaType);\n });\n\n this.rtcClient.on('user-unpublished', (user: IAgoraRTCRemoteUser, mediaType) => {\n // this._logger.debug(`.rtcClient>>[user-unpublished]: mediaType:`, mediaType, ' user:', user);\n this._handleRemoteTrackRemoved(user, mediaType);\n });\n\n\n this.unsubscribeMediaHostUpdateListener = this.webcastAuctionHandler.mediaStreamingHandler.onMediaStreamingHostsUpdated(this._handleWbsStreamingHostUpdated);\n }\n\n\n _handleRemoteTrackAdded = (user:IAgoraRTCRemoteUser, mediaType:AgoraMediaTypeEnum) => {\n this._logger.debug('_handleRemoteTrackAdded: ', user.uid, mediaType, user);\n\n if (mediaType === AgoraMediaTypeEnum.audio) {\n this.availableAudioRemoteUsers.set(user.uid, user);\n\n // if this newly added track is the WBS designated master track, then fire the change event\n if (this.wbsAudioUid === user.uid) {\n this._fireMasterStreamsChanged({ audioRemoteUser: user });\n }\n }\n else if (mediaType === AgoraMediaTypeEnum.video) {\n this.availableVideoRemoteUsers.set(user.uid, user);\n\n // if this newly added track is the WBS designated master track, then fire the change event\n if (this.wbsVideoUid === user.uid) {\n this._fireMasterStreamsChanged({ videoRemoteUser: user });\n }\n }\n else throw new Error(`._handleRemoteTrackAdded: invalid mediaType: '${mediaType}'`); // should never get this error\n };\n\n\n\n _handleRemoteTrackRemoved = (user:IAgoraRTCRemoteUser, mediaType:AgoraMediaTypeEnum) => {\n this._logger.debug('_handleRemoteTrackRemoved: ', user.uid, mediaType, user);\n\n if (mediaType === AgoraMediaTypeEnum.audio) {\n this.availableAudioRemoteUsers.delete(user.uid);\n\n // if this removed track is the WBS designated master track, then fire the change event to tell the UI to unsubscribe+stop-play\n if (this.wbsAudioUid === user.uid) {\n this._fireMasterStreamsChanged({ audioRemoteUser: false });\n }\n }\n else if (mediaType === AgoraMediaTypeEnum.video) {\n this.availableVideoRemoteUsers.delete(user.uid);\n\n // if this removed track is the WBS designated master track, then fire the change event to tell the UI to unsubscribe+stop-play\n if (this.wbsVideoUid === user.uid) {\n this._fireMasterStreamsChanged({ videoRemoteUser: false });\n }\n }\n else throw new Error(`._handleRemoteTrackRemoved: invalid mediaType: '${mediaType}'`); // should never get this error\n };\n\n\n\n _handleWbsStreamingHostUpdated = (update:MediaStreamingHostsUpdateType) => {\n this._logger.debug('_handleWbsStreamingHostUpdated: update:', update);\n\n if (this.wbsAudioUid != update.wbsAudioUid) {\n\n this.wbsAudioUid = update.wbsAudioUid;\n\n let remoteUser;\n\n if (update.wbsAudioUid === this.myAgoraUid) {\n // we are the master RemoteUser! i.e. publisher\n remoteUser = true;\n }\n else if (update.wbsAudioUid) {\n remoteUser = this.availableAudioRemoteUsers.get(update.wbsAudioUid) || null; // ensure value is `null`, to compare below\n }\n else {\n // update.wbsAudioUid is NULL\n remoteUser = false;\n }\n\n // only if there was a valid change\n if (remoteUser !== null) {\n this._fireMasterStreamsChanged({audioRemoteUser: remoteUser});\n }\n }\n\n\n if (this.wbsVideoUid != update.wbsVideoUid) {\n\n this.wbsVideoUid = update.wbsVideoUid;\n\n let remoteUser;\n\n if (update.wbsVideoUid === this.myAgoraUid) {\n // we are the master RemoteUser! i.e. publisher\n remoteUser = true;\n }\n else if (update.wbsVideoUid) {\n remoteUser = this.availableVideoRemoteUsers.get(update.wbsVideoUid) || null; // ensure value is `null`, to compare below\n }\n else {\n // update.wbsVideoUid is NULL\n remoteUser = false;\n }\n\n // only if there was a valid change\n if (remoteUser !== null) {\n this._fireMasterStreamsChanged({videoRemoteUser: remoteUser});\n }\n }\n };\n\n\n _fireMasterStreamsChanged(change:MasterRemoteUsersTypeDef) {\n // this._logger.debug(\"_fireMasterStreamsChanged: change:\", change);\n\n\n if (typeof change.audioRemoteUser !== 'undefined') {\n this.currentMasterRemoteUsers.audioRemoteUser = change.audioRemoteUser;\n }\n if (typeof change.videoRemoteUser !== 'undefined') {\n this.currentMasterRemoteUsers.videoRemoteUser = change.videoRemoteUser;\n }\n\n // notify listener if it exists\n this.listener_remoteMasterStreamsChanged && this.listener_remoteMasterStreamsChanged(change);\n }\n\n\n\n\n async connectAndJoinChannel():Promise {\n try {\n this._registerListeners();\n\n this._logger.log(\".connectAndJoinChannel>init SUCCESS. Setting role `\"+ this.rtcClientRole +\"` and joining channel: \" + this.agoraChannelName);\n\n // await this.rtcClient.setClientRole(this.rtcClientRole);\n\n this.myAgoraUid = await this.rtcClient.join(this.agoraAppId, this.agoraChannelName, this.agoraToken);\n\n this._logger.log(\".connectAndJoinChannel>join[\" + this.agoraChannelName + \"] SUCCESS with UID: \" + this.myAgoraUid);\n }\n catch(ex) {\n this._logger.error(`.connectAndJoinChannel: FAILED channel[${this.rtcClientRole}] role[${this.rtcClientRole}]`, ex);\n }\n }\n\n\n /**\n * register change listener\n */\n onRemoteMasterStreamsChanged(listener:(change:MasterRemoteUsersTypeDef)=>any):()=>void {\n if (this.listener_remoteMasterStreamsChanged) {\n throw 'AgoraService.onRemoteMasterStreamsChanged: listener already registered';\n }\n\n this.listener_remoteMasterStreamsChanged = listener;\n\n // trigger the listener on registration, with the current values\n this.listener_remoteMasterStreamsChanged(this.currentMasterRemoteUsers);\n\n return () => {\n // return a listener unsubscribe function\n this.listener_remoteMasterStreamsChanged = null;\n }\n }\n\n\n destroy() {\n this._logger.debug('.destroy()');\n if (this.rtcClient) {\n this.rtcClient.leave();\n }\n }\n}\n\n\n\n\n\n\nexport class AgoraPublisher extends AbstractAgoraService {\n\n public localMediaDevicesAudio:Array;\n public localMediaDevicesVideo:Array;\n\n public localAudioTrack:IMicrophoneAudioTrack;\n public localVideoTrack:ICameraVideoTrack;\n\n private isPublishActive: boolean = false;\n\n\n constructor(args) {\n super(args);\n (window as any)._dev_agoraPublisher = this;\n }\n\n\n\n\n async scanAndLoadLocalMediaDevices():Promise {\n [this.localMediaDevicesAudio, this.localMediaDevicesVideo] = await Promise.all([\n AgoraRTC.getMicrophones(),\n AgoraRTC.getCameras(),\n ]);\n return this;\n }\n\n\n async createLocalTracks():Promise {\n [this.localAudioTrack, this.localVideoTrack] = await Promise.all([\n AgoraRTC.createMicrophoneAudioTrack(),\n AgoraRTC.createCameraVideoTrack()\n ]);\n return this;\n }\n\n\n async publish() {\n this._logger.debug('.publish() localTracks: audioTrack:', !this.localAudioTrack.muted, ' videoTrack:', !this.localVideoTrack.muted, 'publishActive:', this.isPublishActive);\n\n if (! this.isPublishActive) {\n await this.rtcClient.publish([this.localAudioTrack, this.localVideoTrack]);\n this.isPublishActive = true;\n }\n\n // send WBS message for published stream video/audio\n this.webcastAuctionHandler.controller.sendStreamingHostUpdate(this.myAgoraUid,\n { hasAudio: !this.localAudioTrack.muted, hasVideo: !this.localVideoTrack.muted });\n }\n\n\n async unpublish() {\n await this.rtcClient.unpublish();\n this.isPublishActive = false;\n }\n\n}\n\n\n\n\n\n\n\nexport class AgoraSubscriber extends AbstractAgoraService {\n\n public subscribedRemoteAudioTrack:IRemoteAudioTrack = null;\n public subscribedRemoteVideoTrack:IRemoteVideoTrack = null;\n\n\n constructor(args) {\n super(args);\n (window as any)._dev_agoraSubscriber = this;\n }\n\n\n registerAutoSubscribeToMasterRemoteUsers(listenerFn:(agoraSubscriber:AgoraSubscriber)=>any) {\n this._logger.debug('.registerAutoSubscribeToMasterRemoteUsers()');\n\n const unsubscribeChangeListener = this.onRemoteMasterStreamsChanged(async (change) => {\n\n this._logger.debug('.registerAutoSubscribeToMasterRemoteUsers()>onRemoteMasterStreamsChanged: ', change);\n\n // the newly designated RemoteUser, can be null (falsey) !\n const newAudioRemoteUser:IAgoraRTCRemoteUser = (typeof change.audioRemoteUser === 'object') && change.audioRemoteUser;\n const newAudioRemoteUserUid:UID = newAudioRemoteUser?.uid;\n\n // the currently subscribed RemoteUser, can also be null (falsey) !\n const subscribedAudioRemoteUserUid = this.subscribedRemoteAudioTrack?.getUserId();\n\n\n this._logger.debug('.registerAutoSubscribeToMasterRemoteUsers()>onRemoteMasterStreamsChanged: subscribedAudioRemoteUserUid', subscribedAudioRemoteUserUid);\n\n // if we are subscribed, and the master RemoteUser has gone away or changed, then ...\n if (subscribedAudioRemoteUserUid && (change.audioRemoteUser === false || (newAudioRemoteUserUid && subscribedAudioRemoteUserUid !== newAudioRemoteUserUid))) {\n // unsubscribe\n this.subscribedRemoteAudioTrack = null;\n this._logger.debug('.registerAutoSubscribeToMasterRemoteUsers()>onRemoteMasterStreamsChanged: ', 'UN-subscribe AUDIO -> null');\n const remoteUser = this.availableAudioRemoteUsers.get(subscribedAudioRemoteUserUid);\n if (remoteUser) {\n this._logger.debug('.registerAutoSubscribeToMasterRemoteUsers()>onRemoteMasterStreamsChanged: ', 'UN-subscribe AUDIO', remoteUser);\n await this.rtcClient.unsubscribe(remoteUser, AgoraMediaTypeEnum.audio);\n }\n }\n\n\n // if there's a new RemoteUser designated, and it's different then our current one ...\n if (newAudioRemoteUserUid && subscribedAudioRemoteUserUid !== newAudioRemoteUserUid) {\n // subscribe to it\n this._logger.debug('.registerAutoSubscribeToMasterRemoteUsers()>onRemoteMasterStreamsChanged: ', 'subscribe AUDIO', newAudioRemoteUser);\n this.subscribedRemoteAudioTrack = await this.rtcClient.subscribe(newAudioRemoteUser, AgoraMediaTypeEnum.audio);\n }\n\n // ... and again, for video\n\n const newVideoRemoteUser:IAgoraRTCRemoteUser = (typeof change.videoRemoteUser === 'object') && change.videoRemoteUser;\n const newVideoRemoteUserUid:UID = newVideoRemoteUser?.uid;\n\n const subscribedVideoRemoteUserUid = this.subscribedRemoteVideoTrack?.getUserId();\n\n if (subscribedVideoRemoteUserUid && (change.videoRemoteUser === false || (newVideoRemoteUserUid && subscribedVideoRemoteUserUid !== newVideoRemoteUserUid))) {\n this.subscribedRemoteVideoTrack = null;\n this._logger.debug('.registerAutoSubscribeToMasterRemoteUsers()>onRemoteMasterStreamsChanged: ', 'UN-subscribe VIDEO -> null');\n const remoteUser = this.availableVideoRemoteUsers.get(subscribedVideoRemoteUserUid);\n if (remoteUser) {\n this._logger.debug('.registerAutoSubscribeToMasterRemoteUsers()>onRemoteMasterStreamsChanged: ', 'UN-subscribe VIDEO', remoteUser);\n await this.rtcClient.unsubscribe(remoteUser, AgoraMediaTypeEnum.video);\n }\n }\n\n if (newVideoRemoteUserUid && subscribedVideoRemoteUserUid !== newVideoRemoteUserUid) {\n this._logger.debug('.registerAutoSubscribeToMasterRemoteUsers()>onRemoteMasterStreamsChanged: ', 'subscribe VIDEO', newVideoRemoteUser);\n this.subscribedRemoteVideoTrack = await this.rtcClient.subscribe(newVideoRemoteUser, AgoraMediaTypeEnum.video);\n }\n\n listenerFn(this);\n });\n\n\n return () => {\n unsubscribeChangeListener();\n }\n }\n\n\n}\n\n", "import React from 'react';\nimport {produce, Draft} from 'immer';\nimport classNames from \"classnames\";\nimport {\n AgoraPublisher,\n MEDIA_QUALITY_AUDIO_PROFILES_CODES_MAP,\n MEDIA_QUALITY_VIDEO_PROFILES_CODES_MAP,\n MasterRemoteUsersTypeDef\n} from \"../../services/AgoraService\";\nimport {TaggedLogger} from \"@nextlot/core/utilities\";\nimport AuctionsManager from \"@nextlot/core/webcast/services/AuctionsManager\";\nimport {Tooltip} from \"../floatui_components\";\n\n\nconst _logger = TaggedLogger.get('ClerkMediaStreamingCmp');\n\n\nconst VIDEO_PREVIEW_PLAYER_ELEMENT_ID = 'publisher_container';\n\nconst VIDEO_PREVIEW_WIDTH = 270;\nconst VIDEO_PREVIEW_HEIGHT = VIDEO_PREVIEW_WIDTH * 0.75; // 4:3 ratio\n\n\nconst DEFAULT_STREAM_SETTINGS = {\n audioProfileCode: 'standard',\n videoProfileCode: '640_480_15',\n};\n\n\n\ntype CmpState = Partial<{\n statusLogLines: Array,\n\n showSettingsPanel:boolean|'wait',\n showStatusLogPanel:boolean,\n\n connectStatus:number,\n publisherStatus:number,\n\n streamHasAudio:boolean,\n streamHasVideo:boolean,\n streamProfileCodeForAudio?:string,\n streamProfileCodeForVideo?:string,\n\n newStreamHasAudio:boolean,\n newStreamHasVideo:boolean,\n newStreamProfileCodeForAudio:string,\n newStreamProfileCodeForVideo:string,\n\n isPublishActive:boolean,\n muteAudio:boolean,\n previewVideo:boolean,\n}>;\n\n\nenum StatusLogLevelEnum {\n info = 'info',\n warn = 'warn',\n error = 'error',\n}\ntype StatusLogLineTypeDef = [StatusLogLevelEnum, string];\n\n\ntype LocalMediaDevicesTypeDef = {\n audio:MediaDeviceInfo[],\n video:MediaDeviceInfo[]\n}\n\nenum PublisherStatusEnum {\n initializing = 0,\n connected_ok = 2,\n\n local_devices_enabling = 3,\n local_devices_available = 4,\n\n local_tracks_created = 5,\n\n publish_ok = 7,\n\n connect_error = -1,\n}\n\n\nenum PanelVisibleStatesEnum {\n closed,\n visible,\n visible_locked\n}\n\ntype MediaKind = 'audio'|'video';\ntype MediaKindStreamingSettings = {\n isEnabled: boolean,\n deviceId?: string,\n profileCode?: string,\n}\n\ntype StreamingSettingsTypeDef = Record;\n\n\nconst PublisherStreamingContext = React.createContext({\n // stage: PublisherStatusEnum.initializing,\n // setPublisherState: ()\n});\n\n\nexport default function ClerkMediaStreamingCmp() {\n _logger.debug('.render()');\n\n const refAgoraPublisher = React.useRef(null);\n\n const refPublisherStatusValue = React.useRef(PublisherStatusEnum.initializing);\n const [publisherStatus, setPublisherStatus] = React.useState(PublisherStatusEnum.initializing);\n\n const [statusLogLines, dispatchStatusLogLines] = React.useReducer(\n produce((draft: Draft, action: { type:string, payload?: any }) => {\n switch (action.type) {\n case 'update':\n // append payload to last status line\n draft[draft.length - 1][1] = draft[draft.length - 1][1] + ' ' + action.payload;\n break;\n\n case 'add':\n draft.push(action.payload);\n break;\n }\n }),\n [\n [StatusLogLevelEnum.info, \"Initializing ... \"]\n ]);\n\n const [statusLogPanelVisibleState, setStatusLogPanelVisibleState] = React.useState(PanelVisibleStatesEnum.visible_locked);\n const [settingsPanelVisibleState, setSettingsPanelVisibleState] = React.useState(PanelVisibleStatesEnum.closed);\n\n const [localMediaDevices, setLocalMediaDevices] = React.useState(null);\n\n const [streamingSettings, setStreamingSettings] = React.useState({ audio: { isEnabled: false }, video: { isEnabled: false } });\n\n const [isLocalPublisherAudioMasterStreaming, setIsLocalPublisherAudioMasterStreaming] = React.useState(false);\n const [isLocalPublisherVideoMasterStreaming, setIsLocalPublisherVideoMasterStreaming] = React.useState(false);\n\n const handleRemoteMasterStreamsChanged = (change:MasterRemoteUsersTypeDef) => {\n _logger.debug('agoraPublisher.onRemoteMasterStreamsChanged: change:', change);\n\n if (refPublisherStatusValue.current < PublisherStatusEnum.publish_ok) {\n // ignore the event if we don't have a local publisherStream\n return;\n }\n\n (typeof change.audioRemoteUser === 'object') && setIsLocalPublisherAudioMasterStreaming(false);\n (typeof change.videoRemoteUser === 'object') && setIsLocalPublisherVideoMasterStreaming(false);\n\n };\n\n\n React.useEffect(() => {\n refAgoraPublisher.current = new AgoraPublisher(AuctionsManager.currentWebcastAuctionHandler);\n const agoraPublisher = refAgoraPublisher.current;\n\n dispatchStatusLogLines({ type: 'update', payload: 'OK'});\n\n dispatchStatusLogLines({ type: 'add', payload: [StatusLogLevelEnum.info, 'Connecting ...']})\n\n agoraPublisher.connectAndJoinChannel()\n .then(() => {\n setPublisherStatus(PublisherStatusEnum.connected_ok);\n\n dispatchStatusLogLines({ type: 'update', payload: `CONNECTED [${agoraPublisher.agoraChannelName}]` });\n\n setStatusLogPanelVisibleState(PanelVisibleStatesEnum.closed);\n\n agoraPublisher.onRemoteMasterStreamsChanged(handleRemoteMasterStreamsChanged);\n })\n .catch(() => {\n setPublisherStatus(PublisherStatusEnum.connect_error);\n setStatusLogPanelVisibleState(PanelVisibleStatesEnum.visible_locked);\n })\n\n }, []);\n\n\n\n\n const handleClick_enableDevices = () => {\n\n setPublisherStatus(PublisherStatusEnum.local_devices_enabling);\n\n dispatchStatusLogLines({ type: 'add', payload: [StatusLogLevelEnum.info, 'Scanning local media devices ...']})\n\n refAgoraPublisher.current.scanAndLoadLocalMediaDevices().then((publisher) => {\n dispatchStatusLogLines({ type: 'update', payload: 'OK.'});\n\n setLocalMediaDevices({\n audio: publisher.localMediaDevicesAudio,\n video: publisher.localMediaDevicesVideo,\n });\n\n setStreamingSettings({\n audio: {\n deviceId: publisher.localMediaDevicesAudio[0].deviceId,\n isEnabled: true,\n profileCode: DEFAULT_STREAM_SETTINGS.audioProfileCode,\n },\n video: {\n deviceId: publisher.localMediaDevicesVideo[0].deviceId,\n isEnabled: true,\n profileCode: DEFAULT_STREAM_SETTINGS.videoProfileCode,\n },\n })\n\n setPublisherStatus(PublisherStatusEnum.local_devices_available);\n\n publisher.createLocalTracks().then((publisher) => {\n publisher.localVideoTrack.play(VIDEO_PREVIEW_PLAYER_ELEMENT_ID);\n\n // open the SettingsPanel only after the local tracks are created\n setSettingsPanelVisibleState(PanelVisibleStatesEnum.visible);\n });\n });\n\n }\n\n\n const handleApplyNewStreamingSettings = async (newStreamingSettings:StreamingSettingsTypeDef) => {\n setSettingsPanelVisibleState(PanelVisibleStatesEnum.visible_locked);\n\n const agoraPublisher = refAgoraPublisher.current;\n\n if ((!!newStreamingSettings.video.isEnabled) !== (!!streamingSettings.video.isEnabled)) {\n // use ILocalTrack.setMuted better than .setEnabled\n // see https://docs.agora.io/en/Interactive%20Broadcast/faq/differences_between_setenabled_and_setmuted\n await agoraPublisher.localVideoTrack.setMuted(! newStreamingSettings.video.isEnabled);\n }\n\n if (newStreamingSettings.video.deviceId !== streamingSettings.video.deviceId) {\n await agoraPublisher.localVideoTrack.setDevice(newStreamingSettings.video.deviceId)\n }\n\n if (newStreamingSettings.video.profileCode !== streamingSettings.video.profileCode) {\n await agoraPublisher.localVideoTrack.setEncoderConfiguration(MEDIA_QUALITY_VIDEO_PROFILES_CODES_MAP[newStreamingSettings.video.profileCode || DEFAULT_STREAM_SETTINGS.videoProfileCode]);\n }\n\n\n if ((!!newStreamingSettings.audio.isEnabled) !== (!!streamingSettings.audio.isEnabled)) {\n // use ILocalTrack.setMuted better than .setEnabled\n // see https://docs.agora.io/en/Interactive%20Broadcast/faq/differences_between_setenabled_and_setmuted\n await agoraPublisher.localAudioTrack.setMuted(! newStreamingSettings.audio.isEnabled);\n }\n\n if (newStreamingSettings.audio.deviceId !== streamingSettings.audio.deviceId) {\n await agoraPublisher.localAudioTrack.setDevice(newStreamingSettings.audio.deviceId)\n }\n\n if (newStreamingSettings.audio.profileCode !== streamingSettings.audio.profileCode) {\n // await agoraPublisher.localAudioTrack.set setEncoderConfiguration(MEDIA_QUALITY_AUDIO_PROFILES_CODES_MAP[newStreamingSettings.audio.profileCode || DEFAULT_STREAM_SETTINGS.audioProfileCode]);\n }\n\n setStreamingSettings(newStreamingSettings);\n setSettingsPanelVisibleState(PanelVisibleStatesEnum.closed);\n }\n\n\n\n const handleClick_Publish = () => {\n refAgoraPublisher.current.publish().then((value) => {\n setPublisherStatus(PublisherStatusEnum.publish_ok);\n setIsLocalPublisherAudioMasterStreaming(streamingSettings.audio.isEnabled);\n setIsLocalPublisherVideoMasterStreaming(streamingSettings.video.isEnabled);\n });\n }\n\n\n // Updated with every component re-render and needed to keep the publisherStatus state value up-to-date\n // inside the .onRemoteMasterStreamsChanged event listener instance.\n\n refPublisherStatusValue.current = publisherStatus;\n\n // STAGES:\n // 1. connect+join\n // 2. enable media devices (i.e. allow permission)\n // 3. settings\n\n const isMediaDevicesAvailable = localMediaDevices && (publisherStatus >= PublisherStatusEnum.local_devices_available); // strictly after connected_ok\n\n return (\n \n
\n
\n {\n (publisherStatus >= PublisherStatusEnum.local_devices_enabling)\n ? <>\n
\n\n {\n (publisherStatus === PublisherStatusEnum.local_devices_enabling)\n ?
Enabling local media devices ...
\n : <>\n setSettingsPanelVisibleState(PanelVisibleStatesEnum.closed)}\n localMediaDevices={localMediaDevices}\n publisherStatus={publisherStatus}\n streamingSettings={streamingSettings}\n onApply={handleApplyNewStreamingSettings}\n />\n \n }\n \n :
\n

Setup Media Streaming

\n

Click and if prompted\n please "Allow" your browser to access the camera and microphone.

\n
\n }\n\n\n {\n (statusLogPanelVisibleState !== PanelVisibleStatesEnum.closed)\n &&\n setStatusLogPanelVisibleState(PanelVisibleStatesEnum.closed)} lines={statusLogLines}/>\n }\n
\n\n
\n\n \n\n {\n (isMediaDevicesAvailable)\n &&\n <>\n \n \n }\n\n
\n\n {\n \n {\n publisherStatus >= PublisherStatusEnum.publish_ok && streamingSettings.audio.isEnabled // Streaming is enabled\n ? isLocalPublisherAudioMasterStreaming // I am master streaming audio\n ? <>\n \n \n \n : <>\n \n \n \n : streamingSettings.audio.isEnabled // Streaming is disabled and device is set\n ? <>\n \n \n \n : <>\n \n \n \n }\n \n }\n\n\n {\n \n {\n publisherStatus >= PublisherStatusEnum.publish_ok && streamingSettings.video.isEnabled // Streaming is enabled\n ? isLocalPublisherVideoMasterStreaming // I am master streaming video\n ? <>\n \n \n \n : <>\n \n \n \n : streamingSettings.video.isEnabled // Streaming is disabled and device is set\n ? <>\n \n \n \n : <>\n \n \n \n }\n \n }\n\n
\n {\n (publisherStatus === PublisherStatusEnum.connect_error)\n ? \n \n \n : (publisherStatus < PublisherStatusEnum.connected_ok)\n ? \n \n \n :
\n \n\n  \n\n {\n (publisherStatus >= PublisherStatusEnum.publish_ok && (streamingSettings.audio.isEnabled || streamingSettings.video.isEnabled))\n ? \n LIVE\n
\n : \n }\n
\n }\n
\n\n\n
\n
\n
\n );\n}\n\n\n\nfunction StatusLogPanel({ lines, visibleState, onClose }:{ lines:StatusLogLineTypeDef[], visibleState:PanelVisibleStatesEnum, onClose:Function }) {\n\n const refStatusLogBottomLine = React.useRef(null);\n\n React.useEffect(() => {\n refStatusLogBottomLine.current?.scrollIntoView();\n }, [lines]);\n\n return (\n
\n
\n
Media Streaming Status
\n {\n visibleState !== PanelVisibleStatesEnum.visible_locked\n &&\n \n }\n
\n
\n
    \n {lines.map((logLine, idx) => {\n return (\n
  • \n › \n {logLine[1]}\n
  • \n )\n })}\n
  •  
  • \n
\n
\n
\n );\n}\n\n\n\n\ntype SettingsPanelProps = {\n visibleState:PanelVisibleStatesEnum,\n onClose: ()=>void,\n onApply: (StreamingSettingsTypeDef)=>void,\n localMediaDevices:LocalMediaDevicesTypeDef,\n\n publisherStatus:PublisherStatusEnum,\n streamingSettings:StreamingSettingsTypeDef,\n}\n\n\nfunction cloneStreamingSettings(streamingSettings:StreamingSettingsTypeDef):StreamingSettingsTypeDef {\n return {\n audio: { ... streamingSettings?.audio },\n video: { ... streamingSettings?.video },\n }\n}\n\nfunction SettingsPanel(props:SettingsPanelProps) {\n _logger.debug('SettingsPanel. render: streamingSettings:', props.streamingSettings);\n\n const { visibleState, onClose, onApply, localMediaDevices, publisherStatus, streamingSettings } = props;\n\n const isPublishActive:boolean = publisherStatus >= PublisherStatusEnum.publish_ok;\n\n\n const [newStreamingSettings, dispatchStreamingSettings] = React.useReducer(\n produce((draft: Draft, action: { type:string, payload?: any }) => {\n switch(action.type) {\n case 'init': {\n _logger.debug('SettingsPanel.reducer: INIT', action);\n return cloneStreamingSettings(action.payload);\n }\n\n case 'update': {\n draft[action.payload.media][action.payload.prop] = action.payload.value;\n }\n }\n\n }), streamingSettings, cloneStreamingSettings);\n\n const dispatchUpdateActionStreamingSettings = (media: 'audio'|'video', prop: keyof MediaKindStreamingSettings, value?: any) => {\n dispatchStreamingSettings({ type: 'update', payload: { media, prop, value } });\n }\n\n React.useEffect(() => {\n // every time the panel is visible: re-init the settings!\n // i.e. copy the props settings into a local copy, which will be then handled by the local reducer\n if (visibleState !== PanelVisibleStatesEnum.closed) {\n dispatchStreamingSettings({type: 'init', payload: streamingSettings});\n }\n }, [visibleState]);\n\n let applyButton = null;\n\n // if (hasAtLeastOneTrackChecked) {\n // applyButton = ;\n // }\n // else if (isPublishActive) {\n // // non checked, and active publish => unpublish\n // applyButton = ;\n //\n // }\n // else {\n // }\n\n\n const handleChange_checkboxForMediaKind = (mediaKind:MediaKind) => (evt) => {\n dispatchUpdateActionStreamingSettings(mediaKind, 'isEnabled', evt.target.checked);\n }\n\n\n const handleChange_selectForMediaKind = (mediaKind:MediaKind, prop: keyof MediaKindStreamingSettings) => (evt) => {\n dispatchUpdateActionStreamingSettings(mediaKind, prop, evt.target.value);\n }\n\n\n return (\n
\n
\n Media Streaming Settings\n
\n
\n
\n\n
\n \n\n  \n\n \n\n \n
\n\n
\n \n\n  \n\n \n\n \n
\n\n
\n\n {\n (isPublishActive)\n ?
\n You are streaming live! Changing settings now will briefly interrupt the streaming.\n
\n : (1 == 1)\n ? Need at least one checked\n : null\n }\n\n
\n\n\n
\n\n {visibleState === PanelVisibleStatesEnum.visible_locked ?\n
Applying ...
\n :\n
\n \n \n
\n }\n\n
\n
\n )\n}\n\n\n\n\n//\n// class ClerkMediaStreamingOldCmp extends React.Component<{},CmpState> {\n// private readonly streamingAgoraAppId: string;\n// private readonly streamingAgoraChannelName: string;\n// private readonly streamingAgoraToken: string;\n// private readonly refStatusLogBottomLine: React.RefObject;\n// private _statusLogLines: Array;\n// private agoraService: AgoraPublisher;\n//\n//\n// constructor(props) {\n// super(props);\n// _logger.debug('.constructor()', props);\n//\n// const {streamingAgoraAppId, streamingAgoraChannelName, streamingAgoraToken} = AuctionsManager.currentWebcastAuctionHandler.auctionConnectData;\n//\n// this.streamingAgoraAppId = streamingAgoraAppId;\n// this.streamingAgoraChannelName = streamingAgoraChannelName;\n// this.streamingAgoraToken = streamingAgoraToken;\n//\n// this.refStatusLogBottomLine = React.createRef();\n// this._statusLogLines = [];\n//\n// this.state = {\n// statusLogLines: [],\n//\n// connectStatus: 0,\n// publisherStatus: 0,\n//\n// showSettingsPanel: false,\n// showStatusLogPanel: true,\n//\n// newStreamHasAudio: true,\n// newStreamHasVideo: true,\n//\n// newStreamProfileCodeForAudio: DEFAULT_STREAM_SETTINGS.audioProfileCode,\n// newStreamProfileCodeForVideo: DEFAULT_STREAM_SETTINGS.videoProfileCode,\n//\n// streamHasAudio: false,\n// streamHasVideo: false,\n//\n// muteAudio:false,\n// previewVideo:true,\n// isPublishActive: false\n// };\n//\n//\n// this.agoraService = new AgoraPublisher(this.streamingAgoraAppId);\n// }\n//\n//\n//\n// componentDidMount(): void {\n// this.setState({\n// connectStatus: CONNECT_STATUS_CONNECTING\n// });\n//\n// this._logStatusDebugMessage(`Channel: ${this.streamingAgoraChannelName}`);\n// this._logStatusDebugMessage(`Connecting ...`);\n//\n// this._registerRemoteMasterStreamsChangeListener();\n//\n// this.agoraService.connectAndJoinChannel(this.streamingAgoraChannelName, this.streamingAgoraToken)\n// .then(() => {\n// this.setState({\n// connectStatus: CONNECT_STATUS_CONNECTED_OK,\n// });\n//\n// this._logStatusInfoMessage(`Connect SUCCESSFUL.`);\n//\n// setTimeout(() => {\n// this.setState({\n// showStatusLogPanel: false,\n// });\n// }, 500);\n//\n// }, (reason) => {\n// this.setState({\n// connectStatus: CONNECT_STATUS_CONNECT_ERROR,\n// });\n// this._logStatusErrorMessage(`Connect FAILED: ${reason}`, true);\n// });\n//\n// this._scrollStatusLogListToBottom();\n// }\n//\n//\n//\n//\n//\n// _registerRemoteMasterStreamsChangeListener() {\n// this.agoraService.onRemoteMasterStreamsChanged((change:RemoteMasterStreamsType) => {\n// _logger.debug('_registerRemoteMasterStreamsChangeListener>onRemoteMasterStreamsChanged: change:', change);\n//\n// const myStreamUid = this.agoraService.publisherStream?.getId();\n//\n// if (! myStreamUid || this.state.publisherStatus < PUBLISHER_STATUS_PUBLISH_OK) {\n// // ignore the event if we don't have a local publisherStream\n// _logger.debug('_registerRemoteMasterStreamsChangeListener>onRemoteMasterStreamsChanged: IGNORED! no local publisherStream present or not publishActive');\n// return;\n// }\n//\n// const newHostAudioStreamUid = change.audioStream && change.audioStream.getId();\n// const newHostVideoStreamUid = change.videoStream && change.videoStream.getId();\n//\n//\n// const newState:CmpState = {\n// connectStatus: 0,\n// isPublishActive: false,\n// muteAudio: false,\n// newStreamHasAudio: false,\n// newStreamHasVideo: false,\n// newStreamProfileCodeForAudio: \"\",\n// newStreamProfileCodeForVideo: \"\",\n// previewVideo: false,\n// publisherStatus: 0,\n// showSettingsPanel: undefined,\n// showStatusLogPanel: false,\n// statusLogLines: undefined,\n// streamHasAudio: false,\n// streamHasVideo: false\n// };\n// let lostStreamTrackTypes:Array = [];\n//\n//\n// if (newHostAudioStreamUid && myStreamUid !== newHostAudioStreamUid) {\n// // we are no longer master for audio\n// // mute local audio\n// this.agoraService.publisherStream.muteAudio();\n// // update new react state\n// newState.streamHasAudio = false;\n// newState.newStreamHasAudio = false;\n// lostStreamTrackTypes.push('audio');\n// }\n//\n// if (newHostVideoStreamUid && myStreamUid !== newHostVideoStreamUid) {\n// // we are no longer master for video\n// // mute local video\n// this.agoraService.publisherStream.muteVideo();\n// // update new react state\n// newState.streamHasVideo = false;\n// newState.newStreamHasVideo = false;\n// lostStreamTrackTypes.push('video');\n// }\n//\n//\n// if (lostStreamTrackTypes.length) {\n//\n// this._logStatusWarnMessage(\"Another Clerk is streaming: \" + lostStreamTrackTypes.join(' & '));\n//\n// this.setState(newState, () => {\n// // if both tracks were lost, then unpublish\n// if (lostStreamTrackTypes.length === 2) {\n// _logger.debug(\"_registerRemoteMasterStreamsChangeListener>onRemoteMasterStreamsChanged>setState> lostBothTracks ==> UNPUBLISH\");\n// this.agoraService.unpublish().then(() => {\n// this.setState({\n// publisherStatus: PUBLISHER_STATUS_INIT_OK,\n// })\n// });\n// }\n// });\n// }\n// });\n// }\n//\n//\n//\n// _createOrUpdatePublisherFromCurrentStateNewSettings():Promise {\n// // use the \"new*\" settings in the current state to create a new stream\n// const audio:string|false = this.state.newStreamHasAudio ? this.state.newStreamProfileCodeForAudio : false;\n// const video:string|false = this.state.newStreamHasVideo ? this.state.newStreamProfileCodeForVideo : false;\n// return this.agoraService.createOrUpdatePublisherStream(audio, video);\n// }\n//\n//\n// _applyNewSettingsInStateAndPlayStreamPreview(stream:Stream) {\n// this.setState({\n// showSettingsPanel: false, // ensure SettingsPanel is closed\n// streamHasAudio: this.state.newStreamHasAudio,\n// streamHasVideo: this.state.newStreamHasVideo,\n// streamProfileCodeForAudio: this.state.newStreamProfileCodeForAudio,\n// streamProfileCodeForVideo: this.state.newStreamProfileCodeForVideo,\n// }, () => {\n// if (! stream || stream.isPlaying()) {\n// // ignore when there is no stream or it is already playing\n// return;\n// }\n//\n// stream.play(VIDEO_PREVIEW_PLAYER_ELEMENT_ID, { fit: \"contain\", muted: true });\n// });\n// }\n//\n//\n//\n// handleClick_ShowStatusLogPanel = () => {\n// this.setState({\n// showStatusLogPanel: true\n// })\n// };\n//\n//\n//\n//\n//\n// handleClick_EnableCameraAndMic = () => {\n// this._logStatusDebugMessage('Initializing ...');\n//\n// this.setState({\n//\n// publisherStatus: PUBLISHER_STATUS_INITIALIZING,\n//\n// }, () => {\n// this._createOrUpdatePublisherFromCurrentStateNewSettings()\n// .then((publisherStream:Stream) => {\n//\n// this.setState({\n// publisherStatus: PUBLISHER_STATUS_INIT_OK,\n// }, () => {\n//\n// this._applyNewSettingsInStateAndPlayStreamPreview(publisherStream);\n//\n// this._logStatusInfoMessage('Init SUCCESSFUL.');\n// });\n//\n//\n// }, (reason) => {\n// this.setState({\n// publisherStatus: PUBLISHER_STATUS_INIT_ERROR,\n// });\n// this._logStatusErrorMessage(`Init FAILED: ${reason.msg}`, true);\n// });\n// });\n// };\n//\n//\n//\n// handleClick_ShowSettingsPanel = () => {\n// this.setState({\n// showSettingsPanel: true\n// })\n// };\n//\n// handleChange_checkboxStreamHasAudio = (event) => {\n// this.setState({\n// newStreamHasAudio: event.target.checked\n// });\n// };\n//\n// handleChange_checkboxStreamHasVideo = (event) => {\n// this.setState({\n// newStreamHasVideo: event.target.checked\n// });\n// };\n//\n//\n// handleChange_selectStreamProfileCodeForAudio = (event) => {\n// this.setState({\n// newStreamProfileCodeForAudio: event.target.value\n// })\n// };\n//\n// handleChange_selectStreamProfileCodeForVideo = (event) => {\n// this.setState({\n// newStreamProfileCodeForVideo: event.target.value\n// })\n// };\n//\n//\n//\n//\n//\n// handleClick_SettingsPanelApply = () => {\n// const audioChangedState = this.state.newStreamHasAudio !== this.state.streamHasAudio;\n// const audioChangedProfile = this.state.newStreamHasAudio && (this.state.newStreamProfileCodeForAudio !== this.state.streamProfileCodeForAudio); // only consider profile change if hasVideo\n//\n// const videoChangedState = this.state.newStreamHasVideo !== this.state.streamHasVideo;\n// const videoChangedProfile = this.state.newStreamHasVideo && (this.state.newStreamProfileCodeForVideo !== this.state.streamProfileCodeForVideo); // only consider profile change if hasVideo\n//\n// if ((audioChangedState || audioChangedProfile) || (videoChangedState || videoChangedProfile)) {\n// // if anything about the settings have changed, then we delegate to the agoraService to update\n//\n// _logger.debug('.handleClick_SettingsPanelApply() settings changed: ', this.state);\n//\n//\n// this.setState({\n// showSettingsPanel: 'wait',\n// }, () => {\n//\n// this._createOrUpdatePublisherFromCurrentStateNewSettings()\n// .then((publisherStream) => {\n//\n// this._applyNewSettingsInStateAndPlayStreamPreview(publisherStream);\n//\n// }, (reason) => {\n// // FAILED createOrUpdatePublisherStream\n// _logger.error('.handleClick_SettingsPanelApply>createOrUpdatePublisherStream.fail: ', reason);\n// this._logStatusErrorMessage(`Stream update FAILED: ${reason.msg}`, true);\n// });\n// });\n//\n// }\n// else {\n// // nothing has changed in the settings, just hide the settings panel\n// this.setState({\n// showSettingsPanel: false,\n// });\n// }\n// };\n//\n//\n// handleClick_SettingsPanelCancel = () => {\n// // close panel and reset Audio\n//  \n// \n//
\n//\n//
\n// \n//  \n// \n//
\n//\n// \n// )\n// }\n//\n//\n//\n// renderSettingsPanel() {\n// if ( ! this.state.showSettingsPanel) {\n// return null\n// }\n//\n// const isPublishActive:boolean = this.state.publisherStatus >= PUBLISHER_STATUS_PUBLISH_OK;\n// const hasAtLeastOneTrackChecked:boolean = (this.state.newStreamHasAudio || this.state.newStreamHasVideo);\n// let applyButton = null;\n//\n// if (hasAtLeastOneTrackChecked) {\n// applyButton = ;\n// }\n// else if (isPublishActive) {\n// // non checked, and active publish => unpublish\n// applyButton = ;\n//\n// }\n// else {\n// applyButton = Need at least one checked\n// }\n//\n//\n// return (\n//
\n//
Media Streaming Settings
\n//
\n//\n// {this.renderStreamQualitySettingsForm()}\n//\n// {\n// (isPublishActive) &&\n//
\n// Streaming is active! Changing settings now will briefly interrupt the streaming.\n//
\n// }\n//\n//
\n//\n//\n//
\n//\n// {this.state.showSettingsPanel === 'wait' ?\n//
Applying ...
\n// :\n//
\n// {applyButton}\n// \n//
\n// }\n//\n//
\n//
\n// )\n// }\n//\n//\n//\n//\n//\n//\n// renderStatusLogPanel() {\n// if ( ! this.state.showStatusLogPanel) {\n// return null\n// }\n//\n// return (\n//
\n//
\n//

Media Streaming Status

\n// \n//
\n//
\n//
    \n// {this.state.statusLogLines.map((logLine, idx) => {\n// return (\n//
  • \n// › \n// {logLine[1]}\n//
  • \n// )\n// })}\n//
  •  
  • \n//
\n//
\n//
\n// );\n// }\n//\n//\n//\n//\n//\n// render() {\n// _logger.debug('.render() state: ', this.state);\n//\n// return (\n//
\n//
\n// {\n// (this.state.publisherStatus < PUBLISHER_STATUS_INIT_OK) ?\n//
\n//

Setup Media Streaming

\n//

Click Enable and if prompted\n// please "Allow" your browser to access the camera and microphone.

\n//
\n//\n// :\n//\n//
\n// }\n// {this.renderSettingsPanel()}\n// {this.renderStatusLogPanel()}\n//
\n//\n//
\n// {this.renderControlsWidget()}\n//
\n//
\n// );\n// }\n//\n//\n// }\n", "import {TypedUseSelectorHook, useDispatch, useSelector} from \"react-redux\";\nimport {AppDispatchType, ReduxStateType} from \"./services/DataStore\";\n\n// use throughout your app instead of plain `useDispatch` and `useSelector`\nexport const useAppDispatch: () => AppDispatchType = useDispatch\nexport const useAppSelector: TypedUseSelectorHook = useSelector\n", "import React from \"react\";\nimport {TaggedLogger} from \"@nextlot/core/utilities\";\nimport NetworkAwareBusyOverlayCmp from \"../NetworkAwareBusyOverlayCmp\";\nimport {WebcastStateEnum} from \"@nextlot/core/webcast/data/WebcastDataDomain\";\nimport AuctionsManager from \"@nextlot/core/webcast/services/AuctionsManager\";\nimport {ChannelEnum} from \"@nextlot/core/webcast/redux/actions\";\nimport {useAppSelector} from \"@nextlot/core/webcast/hooks\";\n\n\nconst _logger = TaggedLogger.get('ClerkAuctionInfoHeaderCmp');\n\n\nexport default function ClerkAuctionInfoHeaderCmp() {\n return (\n
\n\n
\n
{AuctionsManager.currentWebcastAuctionHandler.auctionConnectData.auctionName}\n   \n #{AuctionsManager.currentWebcastAuctionHandler.auctionConnectData.auctionId}
\n
\n\n
\n\n \n\n\n
\n \n\n \n
\n
\n\n
\n )\n}\n\n\n\nenum SyncWidgetStatesEnum {\n IDLE_SYNC_NOT_REQUIRED = 1,\n IDLE_SYNC_REQUIRED = 2,\n BUSY_SYNC_IN_PROGRESS = 21,\n}\n\nfunction AuctionDataSyncWidget() {\n const webcastHasBiddingFunctionsEnabled = useAppSelector((state) => state.activeWebcast.webcastStatus.biddingFunctionsEnabled);\n const outOfSyncCacheKey = useAppSelector((state) => state.activeWebcast.webcastAuctionData.remoteLotsCacheKeyOutOfSync);\n\n const [syncWidgetState, setSyncWidgetState] =\n React.useState(outOfSyncCacheKey ? SyncWidgetStatesEnum.IDLE_SYNC_REQUIRED : SyncWidgetStatesEnum.IDLE_SYNC_NOT_REQUIRED);\n\n\n React.useEffect(() => {\n setSyncWidgetState(outOfSyncCacheKey ? SyncWidgetStatesEnum.IDLE_SYNC_REQUIRED : SyncWidgetStatesEnum.IDLE_SYNC_NOT_REQUIRED)\n }, [outOfSyncCacheKey])\n\n\n\n\n const handleClick_SyncApplyNowButton = () => {\n setSyncWidgetState(SyncWidgetStatesEnum.BUSY_SYNC_IN_PROGRESS);\n AuctionsManager.currentWebcastAuctionHandler.controller.sendAuctionDataSyncApply();\n };\n\n\n\n\n if (syncWidgetState === SyncWidgetStatesEnum.IDLE_SYNC_REQUIRED) {\n return (\n
\n out-of-sync:[{outOfSyncCacheKey}]  \n {\n webcastHasBiddingFunctionsEnabled\n ? Must PAUSE before SYNC\n : \n }\n
\n )\n }\n\n else if (syncWidgetState === SyncWidgetStatesEnum.BUSY_SYNC_IN_PROGRESS) {\n return (\n
\n Sync in progress ...\n
\n )\n }\n\n else {\n // IDLE_SYNC_NOT_REQUIRED\n return (\n
\n {\"\\u2713\"} In sync\n
\n )\n }\n}\n\n\n\nfunction ButtonsForWebcastState() {\n const webcastStatus = useAppSelector((state) => state.activeWebcast.webcastStatus);\n\n const handleClick_PauseButton = () => {\n AuctionsManager.currentWebcastAuctionHandler.controller.sendWebcastStatusChange({ pause: ! webcastStatus.paused });\n };\n\n\n\n const handleClick_CloseButton = () => {\n if (window.confirm(\"Confirm closing the webcast event?\")) {\n AuctionsManager.currentWebcastAuctionHandler.controller.sendWebcastStatusChange({ close: true });\n }\n };\n\n const handleClick_StartWebcastButton = () => {\n AuctionsManager.currentWebcastAuctionHandler.controller.sendWebcastStatusChange({ start: true });\n };\n\n\n if (webcastStatus.state === WebcastStateEnum.WEBCAST_STATE__LOBBY) {\n return (\n \n )\n }\n else {\n return (\n
\n \n  \n \n
\n\n )\n }\n}\n\n", "/*! @preserve\n * numeral.js\n * version : 2.0.6\n * author : Adam Draper\n * license : MIT\n * http://adamwdraper.github.com/Numeral-js/\n */\n\n(function (global, factory) {\n if (typeof define === 'function' && define.amd) {\n define(factory);\n } else if (typeof module === 'object' && module.exports) {\n module.exports = factory();\n } else {\n global.numeral = factory();\n }\n}(this, function () {\n /************************************\n Variables\n ************************************/\n\n var numeral,\n _,\n VERSION = '2.0.6',\n formats = {},\n locales = {},\n defaults = {\n currentLocale: 'en',\n zeroFormat: null,\n nullFormat: null,\n defaultFormat: '0,0',\n scalePercentBy100: true\n },\n options = {\n currentLocale: defaults.currentLocale,\n zeroFormat: defaults.zeroFormat,\n nullFormat: defaults.nullFormat,\n defaultFormat: defaults.defaultFormat,\n scalePercentBy100: defaults.scalePercentBy100\n };\n\n\n /************************************\n Constructors\n ************************************/\n\n // Numeral prototype object\n function Numeral(input, number) {\n this._input = input;\n\n this._value = number;\n }\n\n numeral = function(input) {\n var value,\n kind,\n unformatFunction,\n regexp;\n\n if (numeral.isNumeral(input)) {\n value = input.value();\n } else if (input === 0 || typeof input === 'undefined') {\n value = 0;\n } else if (input === null || _.isNaN(input)) {\n value = null;\n } else if (typeof input === 'string') {\n if (options.zeroFormat && input === options.zeroFormat) {\n value = 0;\n } else if (options.nullFormat && input === options.nullFormat || !input.replace(/[^0-9]+/g, '').length) {\n value = null;\n } else {\n for (kind in formats) {\n regexp = typeof formats[kind].regexps.unformat === 'function' ? formats[kind].regexps.unformat() : formats[kind].regexps.unformat;\n\n if (regexp && input.match(regexp)) {\n unformatFunction = formats[kind].unformat;\n\n break;\n }\n }\n\n unformatFunction = unformatFunction || numeral._.stringToNumber;\n\n value = unformatFunction(input);\n }\n } else {\n value = Number(input)|| null;\n }\n\n return new Numeral(input, value);\n };\n\n // version number\n numeral.version = VERSION;\n\n // compare numeral object\n numeral.isNumeral = function(obj) {\n return obj instanceof Numeral;\n };\n\n // helper functions\n numeral._ = _ = {\n // formats numbers separators, decimals places, signs, abbreviations\n numberToFormat: function(value, format, roundingFunction) {\n var locale = locales[numeral.options.currentLocale],\n negP = false,\n optDec = false,\n leadingCount = 0,\n abbr = '',\n trillion = 1000000000000,\n billion = 1000000000,\n million = 1000000,\n thousand = 1000,\n decimal = '',\n neg = false,\n abbrForce, // force abbreviation\n abs,\n min,\n max,\n power,\n int,\n precision,\n signed,\n thousands,\n output;\n\n // make sure we never format a null value\n value = value || 0;\n\n abs = Math.abs(value);\n\n // see if we should use parentheses for negative number or if we should prefix with a sign\n // if both are present we default to parentheses\n if (numeral._.includes(format, '(')) {\n negP = true;\n format = format.replace(/[\\(|\\)]/g, '');\n } else if (numeral._.includes(format, '+') || numeral._.includes(format, '-')) {\n signed = numeral._.includes(format, '+') ? format.indexOf('+') : value < 0 ? format.indexOf('-') : -1;\n format = format.replace(/[\\+|\\-]/g, '');\n }\n\n // see if abbreviation is wanted\n if (numeral._.includes(format, 'a')) {\n abbrForce = format.match(/a(k|m|b|t)?/);\n\n abbrForce = abbrForce ? abbrForce[1] : false;\n\n // check for space before abbreviation\n if (numeral._.includes(format, ' a')) {\n abbr = ' ';\n }\n\n format = format.replace(new RegExp(abbr + 'a[kmbt]?'), '');\n\n if (abs >= trillion && !abbrForce || abbrForce === 't') {\n // trillion\n abbr += locale.abbreviations.trillion;\n value = value / trillion;\n } else if (abs < trillion && abs >= billion && !abbrForce || abbrForce === 'b') {\n // billion\n abbr += locale.abbreviations.billion;\n value = value / billion;\n } else if (abs < billion && abs >= million && !abbrForce || abbrForce === 'm') {\n // million\n abbr += locale.abbreviations.million;\n value = value / million;\n } else if (abs < million && abs >= thousand && !abbrForce || abbrForce === 'k') {\n // thousand\n abbr += locale.abbreviations.thousand;\n value = value / thousand;\n }\n }\n\n // check for optional decimals\n if (numeral._.includes(format, '[.]')) {\n optDec = true;\n format = format.replace('[.]', '.');\n }\n\n // break number and format\n int = value.toString().split('.')[0];\n precision = format.split('.')[1];\n thousands = format.indexOf(',');\n leadingCount = (format.split('.')[0].split(',')[0].match(/0/g) || []).length;\n\n if (precision) {\n if (numeral._.includes(precision, '[')) {\n precision = precision.replace(']', '');\n precision = precision.split('[');\n decimal = numeral._.toFixed(value, (precision[0].length + precision[1].length), roundingFunction, precision[1].length);\n } else {\n decimal = numeral._.toFixed(value, precision.length, roundingFunction);\n }\n\n int = decimal.split('.')[0];\n\n if (numeral._.includes(decimal, '.')) {\n decimal = locale.delimiters.decimal + decimal.split('.')[1];\n } else {\n decimal = '';\n }\n\n if (optDec && Number(decimal.slice(1)) === 0) {\n decimal = '';\n }\n } else {\n int = numeral._.toFixed(value, 0, roundingFunction);\n }\n\n // check abbreviation again after rounding\n if (abbr && !abbrForce && Number(int) >= 1000 && abbr !== locale.abbreviations.trillion) {\n int = String(Number(int) / 1000);\n\n switch (abbr) {\n case locale.abbreviations.thousand:\n abbr = locale.abbreviations.million;\n break;\n case locale.abbreviations.million:\n abbr = locale.abbreviations.billion;\n break;\n case locale.abbreviations.billion:\n abbr = locale.abbreviations.trillion;\n break;\n }\n }\n\n\n // format number\n if (numeral._.includes(int, '-')) {\n int = int.slice(1);\n neg = true;\n }\n\n if (int.length < leadingCount) {\n for (var i = leadingCount - int.length; i > 0; i--) {\n int = '0' + int;\n }\n }\n\n if (thousands > -1) {\n int = int.toString().replace(/(\\d)(?=(\\d{3})+(?!\\d))/g, '$1' + locale.delimiters.thousands);\n }\n\n if (format.indexOf('.') === 0) {\n int = '';\n }\n\n output = int + decimal + (abbr ? abbr : '');\n\n if (negP) {\n output = (negP && neg ? '(' : '') + output + (negP && neg ? ')' : '');\n } else {\n if (signed >= 0) {\n output = signed === 0 ? (neg ? '-' : '+') + output : output + (neg ? '-' : '+');\n } else if (neg) {\n output = '-' + output;\n }\n }\n\n return output;\n },\n // unformats numbers separators, decimals places, signs, abbreviations\n stringToNumber: function(string) {\n var locale = locales[options.currentLocale],\n stringOriginal = string,\n abbreviations = {\n thousand: 3,\n million: 6,\n billion: 9,\n trillion: 12\n },\n abbreviation,\n value,\n i,\n regexp;\n\n if (options.zeroFormat && string === options.zeroFormat) {\n value = 0;\n } else if (options.nullFormat && string === options.nullFormat || !string.replace(/[^0-9]+/g, '').length) {\n value = null;\n } else {\n value = 1;\n\n if (locale.delimiters.decimal !== '.') {\n string = string.replace(/\\./g, '').replace(locale.delimiters.decimal, '.');\n }\n\n for (abbreviation in abbreviations) {\n regexp = new RegExp('[^a-zA-Z]' + locale.abbreviations[abbreviation] + '(?:\\\\)|(\\\\' + locale.currency.symbol + ')?(?:\\\\))?)?$');\n\n if (stringOriginal.match(regexp)) {\n value *= Math.pow(10, abbreviations[abbreviation]);\n break;\n }\n }\n\n // check for negative number\n value *= (string.split('-').length + Math.min(string.split('(').length - 1, string.split(')').length - 1)) % 2 ? 1 : -1;\n\n // remove non numbers\n string = string.replace(/[^0-9\\.]+/g, '');\n\n value *= Number(string);\n }\n\n return value;\n },\n isNaN: function(value) {\n return typeof value === 'number' && isNaN(value);\n },\n includes: function(string, search) {\n return string.indexOf(search) !== -1;\n },\n insert: function(string, subString, start) {\n return string.slice(0, start) + subString + string.slice(start);\n },\n reduce: function(array, callback /*, initialValue*/) {\n if (this === null) {\n throw new TypeError('Array.prototype.reduce called on null or undefined');\n }\n\n if (typeof callback !== 'function') {\n throw new TypeError(callback + ' is not a function');\n }\n\n var t = Object(array),\n len = t.length >>> 0,\n k = 0,\n value;\n\n if (arguments.length === 3) {\n value = arguments[2];\n } else {\n while (k < len && !(k in t)) {\n k++;\n }\n\n if (k >= len) {\n throw new TypeError('Reduce of empty array with no initial value');\n }\n\n value = t[k++];\n }\n for (; k < len; k++) {\n if (k in t) {\n value = callback(value, t[k], k, t);\n }\n }\n return value;\n },\n /**\n * Computes the multiplier necessary to make x >= 1,\n * effectively eliminating miscalculations caused by\n * finite precision.\n */\n multiplier: function (x) {\n var parts = x.toString().split('.');\n\n return parts.length < 2 ? 1 : Math.pow(10, parts[1].length);\n },\n /**\n * Given a variable number of arguments, returns the maximum\n * multiplier that must be used to normalize an operation involving\n * all of them.\n */\n correctionFactor: function () {\n var args = Array.prototype.slice.call(arguments);\n\n return args.reduce(function(accum, next) {\n var mn = _.multiplier(next);\n return accum > mn ? accum : mn;\n }, 1);\n },\n /**\n * Implementation of toFixed() that treats floats more like decimals\n *\n * Fixes binary rounding issues (eg. (0.615).toFixed(2) === '0.61') that present\n * problems for accounting- and finance-related software.\n */\n toFixed: function(value, maxDecimals, roundingFunction, optionals) {\n var splitValue = value.toString().split('.'),\n minDecimals = maxDecimals - (optionals || 0),\n boundedPrecision,\n optionalsRegExp,\n power,\n output;\n\n // Use the smallest precision value possible to avoid errors from floating point representation\n if (splitValue.length === 2) {\n boundedPrecision = Math.min(Math.max(splitValue[1].length, minDecimals), maxDecimals);\n } else {\n boundedPrecision = minDecimals;\n }\n\n power = Math.pow(10, boundedPrecision);\n\n // Multiply up by precision, round accurately, then divide and use native toFixed():\n output = (roundingFunction(value + 'e+' + boundedPrecision) / power).toFixed(boundedPrecision);\n\n if (optionals > maxDecimals - boundedPrecision) {\n optionalsRegExp = new RegExp('\\\\.?0{1,' + (optionals - (maxDecimals - boundedPrecision)) + '}$');\n output = output.replace(optionalsRegExp, '');\n }\n\n return output;\n }\n };\n\n // avaliable options\n numeral.options = options;\n\n // avaliable formats\n numeral.formats = formats;\n\n // avaliable formats\n numeral.locales = locales;\n\n // This function sets the current locale. If\n // no arguments are passed in, it will simply return the current global\n // locale key.\n numeral.locale = function(key) {\n if (key) {\n options.currentLocale = key.toLowerCase();\n }\n\n return options.currentLocale;\n };\n\n // This function provides access to the loaded locale data. If\n // no arguments are passed in, it will simply return the current\n // global locale object.\n numeral.localeData = function(key) {\n if (!key) {\n return locales[options.currentLocale];\n }\n\n key = key.toLowerCase();\n\n if (!locales[key]) {\n throw new Error('Unknown locale : ' + key);\n }\n\n return locales[key];\n };\n\n numeral.reset = function() {\n for (var property in defaults) {\n options[property] = defaults[property];\n }\n };\n\n numeral.zeroFormat = function(format) {\n options.zeroFormat = typeof(format) === 'string' ? format : null;\n };\n\n numeral.nullFormat = function (format) {\n options.nullFormat = typeof(format) === 'string' ? format : null;\n };\n\n numeral.defaultFormat = function(format) {\n options.defaultFormat = typeof(format) === 'string' ? format : '0.0';\n };\n\n numeral.register = function(type, name, format) {\n name = name.toLowerCase();\n\n if (this[type + 's'][name]) {\n throw new TypeError(name + ' ' + type + ' already registered.');\n }\n\n this[type + 's'][name] = format;\n\n return format;\n };\n\n\n numeral.validate = function(val, culture) {\n var _decimalSep,\n _thousandSep,\n _currSymbol,\n _valArray,\n _abbrObj,\n _thousandRegEx,\n localeData,\n temp;\n\n //coerce val to string\n if (typeof val !== 'string') {\n val += '';\n\n if (console.warn) {\n console.warn('Numeral.js: Value is not string. It has been co-erced to: ', val);\n }\n }\n\n //trim whitespaces from either sides\n val = val.trim();\n\n //if val is just digits return true\n if (!!val.match(/^\\d+$/)) {\n return true;\n }\n\n //if val is empty return false\n if (val === '') {\n return false;\n }\n\n //get the decimal and thousands separator from numeral.localeData\n try {\n //check if the culture is understood by numeral. if not, default it to current locale\n localeData = numeral.localeData(culture);\n } catch (e) {\n localeData = numeral.localeData(numeral.locale());\n }\n\n //setup the delimiters and currency symbol based on culture/locale\n _currSymbol = localeData.currency.symbol;\n _abbrObj = localeData.abbreviations;\n _decimalSep = localeData.delimiters.decimal;\n if (localeData.delimiters.thousands === '.') {\n _thousandSep = '\\\\.';\n } else {\n _thousandSep = localeData.delimiters.thousands;\n }\n\n // validating currency symbol\n temp = val.match(/^[^\\d]+/);\n if (temp !== null) {\n val = val.substr(1);\n if (temp[0] !== _currSymbol) {\n return false;\n }\n }\n\n //validating abbreviation symbol\n temp = val.match(/[^\\d]+$/);\n if (temp !== null) {\n val = val.slice(0, -1);\n if (temp[0] !== _abbrObj.thousand && temp[0] !== _abbrObj.million && temp[0] !== _abbrObj.billion && temp[0] !== _abbrObj.trillion) {\n return false;\n }\n }\n\n _thousandRegEx = new RegExp(_thousandSep + '{2}');\n\n if (!val.match(/[^\\d.,]/g)) {\n _valArray = val.split(_decimalSep);\n if (_valArray.length > 2) {\n return false;\n } else {\n if (_valArray.length < 2) {\n return ( !! _valArray[0].match(/^\\d+.*\\d$/) && !_valArray[0].match(_thousandRegEx));\n } else {\n if (_valArray[0].length === 1) {\n return ( !! _valArray[0].match(/^\\d+$/) && !_valArray[0].match(_thousandRegEx) && !! _valArray[1].match(/^\\d+$/));\n } else {\n return ( !! _valArray[0].match(/^\\d+.*\\d$/) && !_valArray[0].match(_thousandRegEx) && !! _valArray[1].match(/^\\d+$/));\n }\n }\n }\n }\n\n return false;\n };\n\n\n /************************************\n Numeral Prototype\n ************************************/\n\n numeral.fn = Numeral.prototype = {\n clone: function() {\n return numeral(this);\n },\n format: function(inputString, roundingFunction) {\n var value = this._value,\n format = inputString || options.defaultFormat,\n kind,\n output,\n formatFunction;\n\n // make sure we have a roundingFunction\n roundingFunction = roundingFunction || Math.round;\n\n // format based on value\n if (value === 0 && options.zeroFormat !== null) {\n output = options.zeroFormat;\n } else if (value === null && options.nullFormat !== null) {\n output = options.nullFormat;\n } else {\n for (kind in formats) {\n if (format.match(formats[kind].regexps.format)) {\n formatFunction = formats[kind].format;\n\n break;\n }\n }\n\n formatFunction = formatFunction || numeral._.numberToFormat;\n\n output = formatFunction(value, format, roundingFunction);\n }\n\n return output;\n },\n value: function() {\n return this._value;\n },\n input: function() {\n return this._input;\n },\n set: function(value) {\n this._value = Number(value);\n\n return this;\n },\n add: function(value) {\n var corrFactor = _.correctionFactor.call(null, this._value, value);\n\n function cback(accum, curr, currI, O) {\n return accum + Math.round(corrFactor * curr);\n }\n\n this._value = _.reduce([this._value, value], cback, 0) / corrFactor;\n\n return this;\n },\n subtract: function(value) {\n var corrFactor = _.correctionFactor.call(null, this._value, value);\n\n function cback(accum, curr, currI, O) {\n return accum - Math.round(corrFactor * curr);\n }\n\n this._value = _.reduce([value], cback, Math.round(this._value * corrFactor)) / corrFactor;\n\n return this;\n },\n multiply: function(value) {\n function cback(accum, curr, currI, O) {\n var corrFactor = _.correctionFactor(accum, curr);\n return Math.round(accum * corrFactor) * Math.round(curr * corrFactor) / Math.round(corrFactor * corrFactor);\n }\n\n this._value = _.reduce([this._value, value], cback, 1);\n\n return this;\n },\n divide: function(value) {\n function cback(accum, curr, currI, O) {\n var corrFactor = _.correctionFactor(accum, curr);\n return Math.round(accum * corrFactor) / Math.round(curr * corrFactor);\n }\n\n this._value = _.reduce([this._value, value], cback);\n\n return this;\n },\n difference: function(value) {\n return Math.abs(numeral(this._value).subtract(value).value());\n }\n };\n\n /************************************\n Default Locale && Format\n ************************************/\n\n numeral.register('locale', 'en', {\n delimiters: {\n thousands: ',',\n decimal: '.'\n },\n abbreviations: {\n thousand: 'k',\n million: 'm',\n billion: 'b',\n trillion: 't'\n },\n ordinal: function(number) {\n var b = number % 10;\n return (~~(number % 100 / 10) === 1) ? 'th' :\n (b === 1) ? 'st' :\n (b === 2) ? 'nd' :\n (b === 3) ? 'rd' : 'th';\n },\n currency: {\n symbol: '$'\n }\n });\n\n \n\n(function() {\n numeral.register('format', 'bps', {\n regexps: {\n format: /(BPS)/,\n unformat: /(BPS)/\n },\n format: function(value, format, roundingFunction) {\n var space = numeral._.includes(format, ' BPS') ? ' ' : '',\n output;\n\n value = value * 10000;\n\n // check for space before BPS\n format = format.replace(/\\s?BPS/, '');\n\n output = numeral._.numberToFormat(value, format, roundingFunction);\n\n if (numeral._.includes(output, ')')) {\n output = output.split('');\n\n output.splice(-1, 0, space + 'BPS');\n\n output = output.join('');\n } else {\n output = output + space + 'BPS';\n }\n\n return output;\n },\n unformat: function(string) {\n return +(numeral._.stringToNumber(string) * 0.0001).toFixed(15);\n }\n });\n})();\n\n\n(function() {\n var decimal = {\n base: 1000,\n suffixes: ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']\n },\n binary = {\n base: 1024,\n suffixes: ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']\n };\n\n var allSuffixes = decimal.suffixes.concat(binary.suffixes.filter(function (item) {\n return decimal.suffixes.indexOf(item) < 0;\n }));\n var unformatRegex = allSuffixes.join('|');\n // Allow support for BPS (http://www.investopedia.com/terms/b/basispoint.asp)\n unformatRegex = '(' + unformatRegex.replace('B', 'B(?!PS)') + ')';\n\n numeral.register('format', 'bytes', {\n regexps: {\n format: /([0\\s]i?b)/,\n unformat: new RegExp(unformatRegex)\n },\n format: function(value, format, roundingFunction) {\n var output,\n bytes = numeral._.includes(format, 'ib') ? binary : decimal,\n suffix = numeral._.includes(format, ' b') || numeral._.includes(format, ' ib') ? ' ' : '',\n power,\n min,\n max;\n\n // check for space before\n format = format.replace(/\\s?i?b/, '');\n\n for (power = 0; power <= bytes.suffixes.length; power++) {\n min = Math.pow(bytes.base, power);\n max = Math.pow(bytes.base, power + 1);\n\n if (value === null || value === 0 || value >= min && value < max) {\n suffix += bytes.suffixes[power];\n\n if (min > 0) {\n value = value / min;\n }\n\n break;\n }\n }\n\n output = numeral._.numberToFormat(value, format, roundingFunction);\n\n return output + suffix;\n },\n unformat: function(string) {\n var value = numeral._.stringToNumber(string),\n power,\n bytesMultiplier;\n\n if (value) {\n for (power = decimal.suffixes.length - 1; power >= 0; power--) {\n if (numeral._.includes(string, decimal.suffixes[power])) {\n bytesMultiplier = Math.pow(decimal.base, power);\n\n break;\n }\n\n if (numeral._.includes(string, binary.suffixes[power])) {\n bytesMultiplier = Math.pow(binary.base, power);\n\n break;\n }\n }\n\n value *= (bytesMultiplier || 1);\n }\n\n return value;\n }\n });\n})();\n\n\n(function() {\n numeral.register('format', 'currency', {\n regexps: {\n format: /(\\$)/\n },\n format: function(value, format, roundingFunction) {\n var locale = numeral.locales[numeral.options.currentLocale],\n symbols = {\n before: format.match(/^([\\+|\\-|\\(|\\s|\\$]*)/)[0],\n after: format.match(/([\\+|\\-|\\)|\\s|\\$]*)$/)[0]\n },\n output,\n symbol,\n i;\n\n // strip format of spaces and $\n format = format.replace(/\\s?\\$\\s?/, '');\n\n // format the number\n output = numeral._.numberToFormat(value, format, roundingFunction);\n\n // update the before and after based on value\n if (value >= 0) {\n symbols.before = symbols.before.replace(/[\\-\\(]/, '');\n symbols.after = symbols.after.replace(/[\\-\\)]/, '');\n } else if (value < 0 && (!numeral._.includes(symbols.before, '-') && !numeral._.includes(symbols.before, '('))) {\n symbols.before = '-' + symbols.before;\n }\n\n // loop through each before symbol\n for (i = 0; i < symbols.before.length; i++) {\n symbol = symbols.before[i];\n\n switch (symbol) {\n case '$':\n output = numeral._.insert(output, locale.currency.symbol, i);\n break;\n case ' ':\n output = numeral._.insert(output, ' ', i + locale.currency.symbol.length - 1);\n break;\n }\n }\n\n // loop through each after symbol\n for (i = symbols.after.length - 1; i >= 0; i--) {\n symbol = symbols.after[i];\n\n switch (symbol) {\n case '$':\n output = i === symbols.after.length - 1 ? output + locale.currency.symbol : numeral._.insert(output, locale.currency.symbol, -(symbols.after.length - (1 + i)));\n break;\n case ' ':\n output = i === symbols.after.length - 1 ? output + ' ' : numeral._.insert(output, ' ', -(symbols.after.length - (1 + i) + locale.currency.symbol.length - 1));\n break;\n }\n }\n\n\n return output;\n }\n });\n})();\n\n\n(function() {\n numeral.register('format', 'exponential', {\n regexps: {\n format: /(e\\+|e-)/,\n unformat: /(e\\+|e-)/\n },\n format: function(value, format, roundingFunction) {\n var output,\n exponential = typeof value === 'number' && !numeral._.isNaN(value) ? value.toExponential() : '0e+0',\n parts = exponential.split('e');\n\n format = format.replace(/e[\\+|\\-]{1}0/, '');\n\n output = numeral._.numberToFormat(Number(parts[0]), format, roundingFunction);\n\n return output + 'e' + parts[1];\n },\n unformat: function(string) {\n var parts = numeral._.includes(string, 'e+') ? string.split('e+') : string.split('e-'),\n value = Number(parts[0]),\n power = Number(parts[1]);\n\n power = numeral._.includes(string, 'e-') ? power *= -1 : power;\n\n function cback(accum, curr, currI, O) {\n var corrFactor = numeral._.correctionFactor(accum, curr),\n num = (accum * corrFactor) * (curr * corrFactor) / (corrFactor * corrFactor);\n return num;\n }\n\n return numeral._.reduce([value, Math.pow(10, power)], cback, 1);\n }\n });\n})();\n\n\n(function() {\n numeral.register('format', 'ordinal', {\n regexps: {\n format: /(o)/\n },\n format: function(value, format, roundingFunction) {\n var locale = numeral.locales[numeral.options.currentLocale],\n output,\n ordinal = numeral._.includes(format, ' o') ? ' ' : '';\n\n // check for space before\n format = format.replace(/\\s?o/, '');\n\n ordinal += locale.ordinal(value);\n\n output = numeral._.numberToFormat(value, format, roundingFunction);\n\n return output + ordinal;\n }\n });\n})();\n\n\n(function() {\n numeral.register('format', 'percentage', {\n regexps: {\n format: /(%)/,\n unformat: /(%)/\n },\n format: function(value, format, roundingFunction) {\n var space = numeral._.includes(format, ' %') ? ' ' : '',\n output;\n\n if (numeral.options.scalePercentBy100) {\n value = value * 100;\n }\n\n // check for space before %\n format = format.replace(/\\s?\\%/, '');\n\n output = numeral._.numberToFormat(value, format, roundingFunction);\n\n if (numeral._.includes(output, ')')) {\n output = output.split('');\n\n output.splice(-1, 0, space + '%');\n\n output = output.join('');\n } else {\n output = output + space + '%';\n }\n\n return output;\n },\n unformat: function(string) {\n var number = numeral._.stringToNumber(string);\n if (numeral.options.scalePercentBy100) {\n return number * 0.01;\n }\n return number;\n }\n });\n})();\n\n\n(function() {\n numeral.register('format', 'time', {\n regexps: {\n format: /(:)/,\n unformat: /(:)/\n },\n format: function(value, format, roundingFunction) {\n var hours = Math.floor(value / 60 / 60),\n minutes = Math.floor((value - (hours * 60 * 60)) / 60),\n seconds = Math.round(value - (hours * 60 * 60) - (minutes * 60));\n\n return hours + ':' + (minutes < 10 ? '0' + minutes : minutes) + ':' + (seconds < 10 ? '0' + seconds : seconds);\n },\n unformat: function(string) {\n var timeArray = string.split(':'),\n seconds = 0;\n\n // turn hours and minutes into seconds and add them all up\n if (timeArray.length === 3) {\n // hours\n seconds = seconds + (Number(timeArray[0]) * 60 * 60);\n // minutes\n seconds = seconds + (Number(timeArray[1]) * 60);\n // seconds\n seconds = seconds + Number(timeArray[2]);\n } else if (timeArray.length === 2) {\n // minutes\n seconds = seconds + (Number(timeArray[0]) * 60);\n // seconds\n seconds = seconds + Number(timeArray[1]);\n }\n return Number(seconds);\n }\n });\n})();\n\nreturn numeral;\n}));\n", "import React from \"react\";\nimport numeral from \"numeral\";\n\n\ntype CmpPropsType = {\n valuesList: Array,\n valuesSign: number,\n buttonTextFormat: string,\n onButtonClick: (valueCents:number) => void,\n currentValue:number,\n};\n\n\nexport default function ClerkIncrementsButtonsGrid(props:CmpPropsType) {\n const {\n valuesList,\n valuesSign,\n onButtonClick,\n buttonTextFormat,\n currentValue,\n } = props;\n\n\n const btnClassName = valuesSign > 0 ? 'btn--increment' : 'btn--decrement';\n\n\n const handleIncrementButtonClick = (valueCents) => (evt) => {\n onButtonClick(valueCents);\n };\n\n\n return (\n
\n {\n valuesList.map(v => v * valuesSign).map((valueCents, cellIdx) => {\n return (\n
\n \n
\n )\n })\n }\n
\n );\n\n};\n\n\nClerkIncrementsButtonsGrid.defaultProps = {\n valueSign: 1,\n buttonTextFormat: '+0,0[.]00',\n currentValue: 0,\n};\n\n", "import React from \"react\";\nimport numeral from \"numeral\";\nimport ClerkIncrementsButtonsGrid from \"./ClerkIncrementsButtonsGrid\";\nimport {TaggedLogger} from \"@nextlot/core/utilities\";\nimport {AuctionsManager, DataStore} from \"@nextlot/core/webcast\";\n\n\nconst _logger = TaggedLogger.get('ClerkRoundStartSetOpeningBidCmp');\n\n\ntype CmpPropsType = {\n currentRoundId: string,\n}\n\n\ntype CmpStateType = Partial<{\n currentRoundId: string,\n openingBidCentsValue: number,\n openingBidInputValue: number,\n canStartRound: boolean,\n inputFocusRequest?: boolean,\n}>\n\nexport default class ClerkRoundStartSetOpeningBidCmp extends React.Component {\n private readonly refInputOpeningBid: any;\n\n\n constructor(props) {\n super(props);\n // _logger.debug('.constructor: ', props);\n\n this.refInputOpeningBid = React.createRef();\n\n this.state = {\n currentRoundId: null,\n openingBidCentsValue: 0,\n openingBidInputValue: 0,\n canStartRound: false,\n }\n }\n\n\n\n static getDerivedStateFromProps(props, state):CmpStateType {\n // reset openingBid to zero any time there's a new currentRoundId\n if (props.currentRoundId !== state.currentRoundId) {\n return {\n currentRoundId: props.currentRoundId,\n openingBidCentsValue: 0,\n openingBidInputValue: 0,\n canStartRound: false,\n inputFocusRequest: true,\n };\n }\n return null;\n }\n\n\n componentDidMount(): void {\n this.refInputOpeningBid.current.focus();\n }\n\n\n componentDidUpdate():void {\n if (this.state.inputFocusRequest) {\n this.setState({\n inputFocusRequest: false,\n }, () => {\n this.refInputOpeningBid.current.focus();\n });\n }\n }\n\n\n\n handleIncrementButtonClick = (valueCents):void => {\n let newValueCents = this.state.openingBidCentsValue + valueCents;\n newValueCents = newValueCents < 0 ? 0 : newValueCents; // no negative values\n\n this.setState({\n openingBidCentsValue: newValueCents,\n openingBidInputValue: numeral(newValueCents / 100).format('0[.]0'),\n canStartRound: (newValueCents > 0),\n inputFocusRequest: true,\n })\n };\n\n\n\n handleOpeningBidValueInputChange = (event):void => {\n const newValueCents = numeral(event.target.value).value() * 100;\n\n this.setState({\n openingBidCentsValue: newValueCents,\n openingBidInputValue: numeral(newValueCents / 100).format('0[.]0'),\n canStartRound: (newValueCents > 0),\n });\n };\n\n\n\n handleFormSubmit = (evt):void => {\n evt.preventDefault();\n evt.stopPropagation();\n\n AuctionsManager.currentWebcastAuctionHandler.controller.sendAskingBidUpdate(this.props.currentRoundId, this.state.openingBidCentsValue);\n };\n\n\n handleResetButtonClick = ():void => {\n this.setState({\n openingBidCentsValue: 0,\n openingBidInputValue: 0,\n canStartRound: false,\n inputFocusRequest: true,\n });\n };\n\n\n\n\n\n render() {\n // _logger.debug('.render(): state:', this.state);\n\n return (\n
\n\n
\n\n
\n \n
\n\n
\n \n
\n\n
\n \n Start round\n \n
\n\n
\n \n Reset\n \n
\n\n
\n\n\n \n\n
\n\n \n
\n )\n }\n}\n\n\n", "import React from \"react\";\nimport {AuctionsManager} from \"@nextlot/core/webcast\";\nimport {RoundStopTypeEnum} from \"@nextlot/core/webcast/data/WebcastDataDomain\";\nimport {Bid} from \"@nextlot/core/webcast/data/data_types_definitions\";\n\n\ntype CmpPropsType = {\n currentRoundId: string,\n currentRoundHighestBid?: Bid\n};\n\n\n\nexport default function ClerkRoundStopButtonsGroup(props:CmpPropsType) {\n const {\n currentRoundId,\n currentRoundHighestBid,\n } = props;\n\n\n\n const handleRoundStopButtonDblClick = (stopType) => (evt) => {\n AuctionsManager.currentWebcastAuctionHandler.controller.sendRoundStop(currentRoundId, stopType);\n };\n\n\n\n return (\n
\n
\n \n \n\n {\n currentRoundHighestBid &&\n \n }\n
\n\n {\n currentRoundHighestBid &&\n
\n \n
\n }\n\n
\n );\n\n};\n", "import React from \"react\";\n\ntype CmpPropsType = {\n valueCents: number,\n allowZero: boolean,\n textIfEmpty?: string,\n className?: string,\n onClick?: ()=>void,\n}\n\n// @ts-ignore\nconst IntlNumberFormat = new Intl.NumberFormat({ style: 'decimal', useGrouping: true, maximumSignificantDigits: 2 });\n\n\n\nexport function formatValueCents(valueCents:number, textIfEmpty:string = '', allowZero:boolean = false):string {\n const fallbackText:string = textIfEmpty || '';\n return Number.isInteger(valueCents) && (allowZero || valueCents !== 0) ? IntlNumberFormat.format(valueCents / 100.0) : fallbackText;\n}\n\n\nexport default function NumberDisplay(props:CmpPropsType) {\n return {formatValueCents(props.valueCents, props.textIfEmpty)};\n}\n\n\nNumberDisplay.formatValueCents = formatValueCents;\n", "import React from 'react';\nimport NumberDisplay from \"../NumberDisplay\";\nimport {TaggedLogger} from \"@nextlot/core/utilities\";\n\n\ntype RootCmpPropsType = {\n label:string,\n valueCents: number,\n textForEmptyValue?: string,\n validateAndSubmitNewValueCents: (valueCents:number)=>string|null, // string=validation-error\n\n componentClassName?: string,\n numberDisplayClassName?: string,\n}\n\n\n\nconst _logger = TaggedLogger.get('ClerkBiddingEditableNumericDisplayRowCmp');\n\n\n\nexport default function ClerkBiddingEditableNumericDisplayRowCmp(props:RootCmpPropsType) {\n const refInput = React.useRef();\n const [isEditMode, setIsEditMode] = React.useState(false);\n const [validationError, setValidationError] = React.useState(null);\n const [inputRawValue, setInputRawValue] = React.useState('');\n\n React.useEffect(() => {\n if (isEditMode) {\n refInput.current?.focus();\n }\n else {\n setInputRawValue('');\n setValidationError(null);\n }\n }, [isEditMode]);\n\n\n const handleOnClick_AskValue = () => {\n if (!isEditMode) {\n setIsEditMode(true);\n }\n }\n\n const handleOnClick_ToggleEditIcon = () => {\n setIsEditMode(prevState => (!prevState));\n }\n\n const handleOnSubmit_Form = (evt) => {\n evt.preventDefault();\n\n const valueFloat:number = parseFloat(inputRawValue);\n if (! valueFloat) {\n setValidationError('Must be a number');\n return\n }\n const valueCents = valueFloat * 100;\n if (valueCents <= 0) {\n setValidationError('Must be greater than 0');\n return\n }\n\n const errorMessage = props.validateAndSubmitNewValueCents(valueCents);\n\n if (errorMessage) {\n setValidationError(errorMessage);\n }\n else {\n setValidationError(null);\n }\n }\n\n\n const handleOnChange_Input = (evt) => {\n setInputRawValue(evt.target.value);\n }\n\n const handleOnKeyUp_Input = (evt) => {\n if (evt.keyCode === 27) {\n // reset\n setValidationError(null);\n }\n }\n\n const handleOnBlur_Input = (evt) => {\n if (inputRawValue === '') {\n // reset\n setValidationError(null);\n }\n }\n\n\n const inputValidClassName:string = validationError ? 'is-invalid' : '';\n\n return (\n
\n
{props.label}
\n
\n \n\n \n {\n isEditMode\n ? \n : \n }\n \n\n\n {\n isEditMode\n &&\n
\n \n \n
\n }\n
\n
\n )\n}\n\n\n\n//\n// type RootCmpStateType = Partial<{\n// isEditMode: boolean,\n// inputValue: number|'',\n// isValidating: boolean,\n// validationError: string|false|null, // null=not-validated; string=invalid; false=valid\n// submittedValueCents: number|false,\n// }>\n//\n// const initialResetState:RootCmpStateType = {\n// isEditMode: false,\n// inputValue: '',\n// validationError: null,\n// isValidating: false,\n// submittedValueCents: false,\n// };\n//\n//\n// class OLD_COMPONENT extends React.Component{\n// protected readonly refInput: React.RefObject;\n//\n//\n// constructor(props) {\n// super(props);\n// this.refInput = React.createRef();\n// this.state = {\n// ...initialResetState\n// };\n// }\n//\n// componentDidUpdate(prevProps: RootCmpPropsType): void {\n// // _logger.debug('.componentDidUpdate: ', { prevProps, this_props: this.props, this_state: this.state });\n//\n// if (prevProps.valueCents !== this.props.valueCents) {\n// // we have a new value coming from the server, then ...\n//\n// // if we successfully submitted a value, and ...\n// if (this.state.isEditMode && this.state.submittedValueCents) {\n// // the value we submitted is the same as the received value\n// if (this.state.submittedValueCents === this.props.valueCents) {\n// // reset the component state\n// this.setState({\n// ...initialResetState\n// });\n// }\n// else {\n// // it's not the value we submitted\n// // => our value is invalid, and the server actually didn't accept our value\n// this.setState({\n// submittedValueCents: null,\n// validationError: 'Invalid value (server rejected)',\n// isValidating: false,\n// })\n// }\n// }\n// }\n// }\n//\n//\n// handleOnClick_AskValue = () => {\n// if ( ! this.state.isEditMode) {\n// this.setState({\n// isEditMode: true,\n// }, () => {\n// this.state.isEditMode && this.refInput.current && this.refInput.current.focus();\n// })\n// }\n// };\n//\n//\n// handleOnClick_ToggleEditIcon = (evt) => {\n// evt.preventDefault();\n//\n// this.setState({\n// isEditMode: ! this.state.isEditMode\n// }, () => {\n// this.state.isEditMode && this.refInput.current && this.refInput.current.focus();\n// });\n// };\n//\n//\n// handleOnSubmit_Form = (evt) => {\n// evt.stopPropagation();\n// evt.preventDefault();\n//\n// if (! this.state.isEditMode) {\n// // do nothing if we're not in edit mode -- should never get here\n// return;\n// }\n//\n// this.setState({\n// isValidating: true,\n// }, () => {\n//\n// const validateAndSubmitResult = this.props.validateAndSubmitNewValueCents(this.state.inputValue);\n//\n// let newState:RootCmpStateType;\n// // if result is an integer => success\n// if (Number.isInteger(validateAndSubmitResult)) {\n// newState = {\n// validationError: false,\n// submittedValueCents: validateAndSubmitResult as number,\n// };\n// }\n// else {\n// newState = {\n// validationError: validateAndSubmitResult as string,\n// submittedValueCents: false,\n// };\n// }\n//\n// this.setState({\n// ...newState,\n// isValidating: false,\n// });\n//\n// });\n// };\n//\n//\n// handleOnChange_Input = (evt) => {\n// this.setState({\n// inputValue: evt.target.value,\n// })\n// };\n//\n// handleOnKeyUp_Input = (evt) => {\n// if (evt.keyCode === 27) {\n// this.setState({\n// ...initialResetState\n// });\n// }\n// };\n//\n// handleOnBlur_Input = () => {\n// if (this.state.inputValue === '') {\n// this.setState({\n// ...initialResetState\n// })\n//\n// }\n// };\n//\n//\n//\n// render() {\n// // _logger.debug('.render: this.state', this.state, 'this.props');\n//\n// let inputValidClassName:string = this.state.validationError ? 'is-invalid' : '';\n//\n// return (\n//
\n//
{this.props.label}
\n//
\n// \n//\n// {\n// this.state.isEditMode\n// ? \n// : \n// }\n//\n//\n// {\n// this.state.isEditMode &&\n//
\n// \n// \n//
\n// }\n//
\n//
\n// )\n// }\n// }\n", "import React from \"react\";\nimport {useAppSelector} from \"@nextlot/core/webcast/hooks\";\nimport {AuctionsManager} from \"@nextlot/core/webcast\";\nimport NumberDisplay from \"../NumberDisplay\";\nimport classNames from \"classnames\";\nimport {Bid, OnlineBid} from \"@nextlot/core/webcast/data/data_types_definitions\";\nimport {TaggedLogger} from \"@nextlot/core/utilities\";\n\n\nconst _logger = TaggedLogger.get('ClerkPlaceFloorAndOnlineBidButtonsStack');\n\n\n\n/**\n * @return state [Array(3)]\n * visibleState:-1|0|1\n * 0=not_visible, -1=visible_disabled, 1=visible_enabled\n * amountCents?:number\n * when visibleState=1, amount of cents to place as bid\n * raiseToAmountCents?:number\n * when visibleState=1 and amountCents=0, if the button will raise up the bid to the secondBid maximum\n */\nfunction calculatePlaceOnlineBidState(askingBidValue:number, highestBid:Bid, firstOnlineBid:OnlineBid|null, secondOnlineBid:OnlineBid|null):[visibleState:-1|0|1, amountCents?:number, raiseToAmountCents?:number] {\n if (!firstOnlineBid) {\n // no online bid\n return [0];\n }\n\n if (!askingBidValue) {\n // no asking bid, waiting for clerk to set increment\n return [-1];\n }\n\n const onlineMinBidAmountCents = (firstOnlineBid.isSecret && secondOnlineBid) ? secondOnlineBid.maximumValue : firstOnlineBid.value;\n\n if (askingBidValue <= onlineMinBidAmountCents) {\n // always match the asking bid when possible\n\n if (!highestBid) {\n // is this the first bid? we can't raise, we must match asking\n return [1, askingBidValue];\n }\n else if (firstOnlineBid.userId === highestBid?.userId) {\n // it's not the first bid, must avoid out-bidding thyself\n return [-1];\n }\n else if (secondOnlineBid) {\n // after the first bid, always raise the bid up-to the second bidder (if exists)\n return [1, 0, onlineMinBidAmountCents];\n }\n else {\n // when no 2nd bidder, then match the asking bid\n return [1, askingBidValue];\n }\n }\n else if (askingBidValue <= firstOnlineBid.maximumValue) {\n // asking bid is over the min bid, check if we can bid towards the maximum\n if (firstOnlineBid.userId === highestBid?.userId) {\n // must avoid out-bidding thyself\n return [-1];\n }\n else {\n return [1, askingBidValue];\n }\n }\n else {\n // asking is over the maximum, we're outbid, no more bidding\n return [-1];\n }\n}\n\n\nexport function ClerkPlaceFloorAndOnlineBidButtonsStack() {\n\n const currentRoundId = useAppSelector((state) => state.activeWebcast.webcastCurrentRoundBidding.roundId);\n const firstOnlineBid = useAppSelector((state) => state.activeWebcast.webcastCurrentRoundBidding.firstOnlineBid);\n const secondOnlineBid = useAppSelector((state) => state.activeWebcast.webcastCurrentRoundBidding.secondOnlineBid);\n const askingBidValue = useAppSelector((state) => state.activeWebcast.webcastCurrentRoundBidding.askingBidValue);\n const highestBid = useAppSelector((state) => state.activeWebcast.webcastCurrentRoundBidding.highestBid);\n\n\n const handleClick_FloorBidButton = () => {\n AuctionsManager.currentWebcastAuctionHandler.controller.sendBidPlace(currentRoundId, askingBidValue);\n };\n\n\n const [placeOnlineBidButtonVisibleState, placeOnlineBidCents, placeOnlineBidRaiseToAmountCents] = calculatePlaceOnlineBidState(askingBidValue, highestBid, firstOnlineBid, secondOnlineBid);\n\n const handleClick_PreBid = () => {\n AuctionsManager.currentWebcastAuctionHandler.controller.sendPreBidPlace(currentRoundId, firstOnlineBid.userId, placeOnlineBidCents);\n };\n\n\n return (\n
\n\n \n\n {\n (placeOnlineBidButtonVisibleState !== 0)\n &&\n
\n \n\n {\n (placeOnlineBidButtonVisibleState > 0)\n &&\n (\n (placeOnlineBidCents === 0 && placeOnlineBidRaiseToAmountCents)\n ?
bid up to {NumberDisplay.formatValueCents(placeOnlineBidRaiseToAmountCents)}
\n :
for {NumberDisplay.formatValueCents(placeOnlineBidCents)}
\n )\n }\n\n
\n }\n
\n )\n}\n\n", "import React from \"react\";\nimport ClerkIncrementsButtonsGrid from \"./ClerkIncrementsButtonsGrid\";\nimport ClerkRoundStopButtonsGroup from \"./ClerkRoundStopButtonsGroup\";\nimport ClerkBiddingEditableNumericDisplayRowCmp from \"./ClerkBiddingEditableNumericDisplayRowCmp\";\nimport {TaggedLogger} from \"@nextlot/core/utilities\";\nimport {AuctionsManager, DataStore} from \"@nextlot/core/webcast\";\nimport {useAppSelector} from \"@nextlot/core/webcast/hooks\";\nimport {ClerkPlaceFloorAndOnlineBidButtonsStack} from \"./ClerkPlaceFloorAndOnlineBidButtonsStack\";\n\n\nconst _logger = TaggedLogger.get('ClerkRoundStartUpdateOpeningBidCmp');\n\n\n\nexport default function ClerkRoundStartUpdateOpeningBidCmp() {\n\n const currentRoundId = useAppSelector((state) => state.activeWebcast.webcastCurrentRoundBidding.roundId);\n const askingBidValue = useAppSelector((state) => state.activeWebcast.webcastCurrentRoundBidding.askingBidValue);\n\n const handleOnClick_IncrementButton = (centsValue:number) => {\n const newCentsValue = Math.max(1, askingBidValue + centsValue); // avoid 0 or negative values\n AuctionsManager.currentWebcastAuctionHandler.controller.sendAskingBidUpdate(currentRoundId, newCentsValue);\n };\n\n const handleValidateAndSubmitNewValue_AskBid = (valueCents:number):string|null => {\n if (valueCents === askingBidValue) {\n return 'Must be different then current asking bid'\n }\n\n AuctionsManager.currentWebcastAuctionHandler.controller.sendAskingBidUpdate(currentRoundId, valueCents);\n\n // if validation ok, return null\n return null;\n };\n\n\n\n return (\n
\n\n \n\n\n
\n\n
\n\n \n\n
\n\n \n
\n\n\n\n \n\n
\n\n \n\n
\n )\n}\n", "import React from \"react\";\nimport ClerkIncrementsButtonsGrid from \"./ClerkIncrementsButtonsGrid\";\nimport ClerkRoundStopButtonsGroup from \"./ClerkRoundStopButtonsGroup\";\nimport ClerkBiddingEditableNumericDisplayRowCmp from \"./ClerkBiddingEditableNumericDisplayRowCmp\";\nimport NumberDisplay from \"../NumberDisplay\";\nimport {BidReviseTypeEnum} from \"@nextlot/core/webcast/data/WebcastDataDomain\";\nimport {Participant} from \"@nextlot/core/webcast/data/data_types_definitions\";\nimport {TaggedLogger} from \"@nextlot/core/utilities\";\nimport {AuctionsManager, DataStore} from \"@nextlot/core/webcast\";\nimport {useAppSelector} from \"@nextlot/core/webcast/hooks\";\nimport {ClerkPlaceFloorAndOnlineBidButtonsStack} from \"./ClerkPlaceFloorAndOnlineBidButtonsStack\";\n\n\nconst _logger = TaggedLogger.get('ClerkRoundBiddingWithBidsReceivedCmp');\n\n\n\nexport default function ClerkRoundBiddingWithBidsReceivedCmp() {\n const myUserId = AuctionsManager.currentWebcastAuctionHandler.auctionConnectData.participantId;\n\n const currentRoundId = useAppSelector((state) => state.activeWebcast.webcastCurrentRoundBidding.roundId);\n const askingBidValue = useAppSelector((state) => state.activeWebcast.webcastCurrentRoundBidding.askingBidValue);\n const bidIncrement = useAppSelector((state) => state.activeWebcast.webcastCurrentRoundBidding.bidIncrement);\n const highestBid = useAppSelector((state) => state.activeWebcast.webcastCurrentRoundBidding.highestBid);\n const participantsByUserId = useAppSelector((state) => state.activeWebcast.webcastParticipants.mapByUserId);\n\n\n\n const sendAskingBidUpdateMessage = (centsValue:number) => {\n AuctionsManager.currentWebcastAuctionHandler.controller.sendAskingBidUpdate(currentRoundId, centsValue);\n }\n\n\n const handleIncrementButtonClick = (centsValue:number) => {\n const newCentsValue = Math.max(1, highestBid.value + centsValue); // avoid 0 or negative values\n sendAskingBidUpdateMessage(newCentsValue);\n };\n\n\n\n const handleValidateAndSubmitNewValue_AskBid = (valueCents:number):string|null => {\n if (valueCents <= highestBid.value) {\n return 'Must be greater than highest bid'\n }\n\n if (valueCents === askingBidValue) {\n return 'Must be different then current asking bid'\n }\n\n sendAskingBidUpdateMessage(valueCents);\n\n // if validation ok, return null\n return null;\n };\n\n\n\n const handleValidateAndSubmitNewValue_Increment = (valueCents:number):string|null => {\n sendAskingBidUpdateMessage(highestBid.value + valueCents);\n // if validation ok, return null\n return null;\n };\n\n\n const handleClick_BidReviseOverride = () => {\n AuctionsManager.currentWebcastAuctionHandler.controller.sendBidRevise(currentRoundId, BidReviseTypeEnum.OVERRIDE_BY_FLOOR, highestBid.value);\n };\n\n const handleClick_BidReviseReverse = () => {\n AuctionsManager.currentWebcastAuctionHandler.controller.sendBidRevise(currentRoundId, BidReviseTypeEnum.REVERSE, highestBid.value);\n };\n\n const disableFloorBid = ! bidIncrement;\n\n\n const highestBidIsInternet = highestBid && highestBid.userId !== myUserId;\n\n const highestBidParticipant:Participant = participantsByUserId.get(highestBid.userId);\n const highestBidParticipantPersonName:string = highestBidParticipant ? highestBidParticipant.bidderPersonName : null;\n\n return (\n
\n\n \n\n
\n\n\n
\n\n
\n
Highest:
\n
\n \n
{highestBid.bidderDisplay}
\n
{highestBidParticipantPersonName}
\n
\n
\n\n\n\n \n\n\n\n \n\n
\n\n\n {\n highestBid\n &&\n
\n \n
 
\n \n
\n }\n\n \n
\n\n\n \n\n
\n )\n}\n\n\n\n\n\n", "import React from \"react\";\nimport {connect} from \"react-redux\";\nimport NumberDisplay from \"../NumberDisplay\";\nimport {Bid, Lot, Participant} from \"@nextlot/core/webcast/data/data_types_definitions\";\nimport {ReduxActiveWebcastSubStateType} from \"@nextlot/core/webcast/redux/reducerActiveWebcast\";\nimport {ReduxWebcastCurrentRoundType} from \"@nextlot/core/webcast/redux/webcast/reducerWebcastCurrentRound\";\nimport {ReduxWebcastCurrentRoundBiddingType} from \"@nextlot/core/webcast/redux/webcast/reducerWebcastCurrentRoundBidding\";\nimport {RoundStopTypeEnum, RoundTypeEnum} from \"@nextlot/core/webcast/data/WebcastDataDomain\";\n\n\n\n\ntype RootCmpPropsType = {\n currentRound: ReduxWebcastCurrentRoundType,\n currentRoundBidding: ReduxWebcastCurrentRoundBiddingType,\n lotsMapById: Map,\n participantsMapByUserId: Map,\n}\n\n\nfunction renderWinningBid(winningBid:Bid) {\n return (\n
\n

Winning Bid:

\n
\n

{NumberDisplay.formatValueCents(winningBid.value)}

\n
{winningBid.bidderDisplay}
\n
\n
\n )\n}\n\n\nfunction renderContent(props:RootCmpPropsType) {\n const {currentRound, currentRoundBidding, lotsMapById, participantsMapByUserId} = props;\n\n if ((currentRound.stopType === RoundStopTypeEnum.SOLD || currentRound.stopType === RoundStopTypeEnum.PENDING) &&\n (currentRound.roundType === RoundTypeEnum.GROUP_CHOICE || currentRound.roundType === RoundTypeEnum.GROUP_CHOICE_REOPEN) && // over-kill to check roundType too, but for consistency clarity\n (currentRoundBidding.choiceLotsSelection && currentRoundBidding.choiceLotsSelection.length)) {\n // render *closing* a CHOICE|CHOICE_REOPEN after lots were assigned by clerk\n\n if (currentRound.stopType === RoundStopTypeEnum.SOLD) {\n //\n }\n else {\n // PENDING\n }\n\n return (\n \n

Lots assigned

\n\n {currentRoundBidding.choiceLotsSelection\n .map(pair => {\n const lotId = pair[0];\n const lot: Lot = lotsMapById.get(lotId);\n const userId = pair[1];\n const participant: Participant | Bid = participantsMapByUserId.get(userId) || currentRoundBidding.highestBid;\n\n return { lot, participant };\n })\n .sort((a:{lot:Lot, participant:Participant}, b:{lot:Lot, participant:Participant}) => (a.lot.orderIdx - b.lot.orderIdx))\n .map(({ lot, participant }:{lot:Lot, participant:Participant}) => {\n return (\n
#{lot.number} {'\\u27F9'} {participant.bidderDisplay}
\n )\n })\n }\n
\n );\n\n }\n else {\n // render *stopping* any type of round\n\n switch (currentRound.stopType) {\n case RoundStopTypeEnum.CANCEL:\n return

CANCEL

;\n\n case RoundStopTypeEnum.NO_SALE:\n return

NO SALE

;\n\n case RoundStopTypeEnum.SOLD:\n return (\n \n

SOLD!

\n {renderWinningBid(currentRoundBidding.highestBid)}\n
\n );\n\n case RoundStopTypeEnum.PENDING:\n return (\n \n

PENDING

\n {renderWinningBid(currentRoundBidding.highestBid)}\n
\n );\n default:\n if (process.env.NODE_ENV === \"development\")\n return

!!! INVALID Round.stopType: {currentRound.stopType}

\n }\n }\n\n\n}\n\n\n\nconst ClerkRoundStopInfoCmp = (props:RootCmpPropsType) => {\n\n /*\n render logic:\n\n if stopType==SOLD|PENDING && roundType == CHOICE|CHOICE_REOPEN && currentRoundBidding.choiceLotsSelection.length\n => show lots assigned to each Participant\n else\n => show stopType + winningBid\n */\n\n return (\n
\n {renderContent(props)}\n
\n );\n};\n\nexport default connect(({ activeWebcast }: {activeWebcast:ReduxActiveWebcastSubStateType}) => {\n return {\n currentRound: activeWebcast.webcastCurrentRound,\n currentRoundBidding: activeWebcast.webcastCurrentRoundBidding,\n lotsMapById: activeWebcast.webcastAuctionData.lotsMapById,\n participantsMapByUserId: activeWebcast.webcastParticipants.mapByUserId,\n };\n})(ClerkRoundStopInfoCmp);\n\n\n", "import React from \"react\";\nimport {connect} from \"react-redux\";\nimport {Bid, Lot, Participant} from \"@nextlot/core/webcast/data/data_types_definitions\";\nimport {ReduxActiveWebcastSubStateType} from \"@nextlot/core/webcast/redux/reducerActiveWebcast\";\nimport {ReduxWebcastCurrentRoundType} from \"@nextlot/core/webcast/redux/webcast/reducerWebcastCurrentRound\";\nimport {TaggedLogger} from \"@nextlot/core/utilities\";\nimport {AuctionsManager} from \"@nextlot/core/webcast\";\nimport {ReduxWebcastCurrentRoundBiddingType} from \"@nextlot/core/webcast/redux/webcast/reducerWebcastCurrentRoundBidding\";\nimport {RoundStopTypeEnum, RoundTypeEnum} from \"@nextlot/core/webcast/data/WebcastDataDomain\";\nimport {ReduxWebcastAuctionDataType} from \"@nextlot/core/webcast/redux/webcast/reducerWebcastAuctionData\";\n\ntype RootCmpPropsType = {\n currentRound: ReduxWebcastCurrentRoundType,\n currentRoundBidding: ReduxWebcastCurrentRoundBiddingType,\n auctionData: ReduxWebcastAuctionDataType,\n participantsByUserId: Map,\n}\n\n\ntype RootCmpStateType = {\n lotsSelection: {}\n}\n\n\nconst _logger = TaggedLogger.get('ClerkRoundChoiceLotsSelectConfirmCmp');\n\nclass ClerkRoundChoiceLotsSelectConfirmCmp extends React.Component {\n private readonly clerkUserId: number;\n\n constructor(props) {\n super(props);\n _logger.debug('.constructor() props:', props);\n\n // we are the Clerk, get the participantId\n this.clerkUserId = AuctionsManager.currentWebcastAuctionHandler.auctionConnectData.participantId;\n\n this.state = {\n lotsSelection: {}\n };\n }\n\n\n\n isLotInputRadioChecked = (lotId:number, userId:number) => {\n const radioInputName = `lot_${lotId}`;\n const currentRoundBidding:ReduxWebcastCurrentRoundBiddingType = this.props.currentRoundBidding;\n return ((this.state.lotsSelection[radioInputName] || currentRoundBidding.choiceLotsSelectionMap.get(lotId)) === userId);\n };\n\n\n\n handleChange_LotSelectInputRadio = (lotId:number, selectedUserId:number) => (evt) => {\n this.setState({\n lotsSelection: {\n ...this.state.lotsSelection,\n [`lot_${lotId}`]: selectedUserId,\n }\n })\n };\n\n\n handleClick_SelectAllButton = (userId:number) => (evt) => {\n const newStateLotsSelection = {\n ...this.state.lotsSelection\n };\n this.props.currentRound.lotsIds.forEach((lotId:number) => {\n newStateLotsSelection[`lot_${lotId}`] = userId;\n });\n this.setState({\n lotsSelection: newStateLotsSelection\n })\n };\n\n\n _computeSelectionLotsIdsAndUsersIdsFromState():{ lotsIds:Array, usersIds:Array } {\n _logger.debug('_computeSelectionLotsIdsAndUsersIdsFromState: ', this.state.lotsSelection);\n const currentRoundBidding:ReduxWebcastCurrentRoundBiddingType = this.props.currentRoundBidding;\n const lotsIds = [];\n const usersIds = [];\n this.props.currentRound.lotsIds.forEach((lotId) => {\n const radioInputName = `lot_${lotId}`;\n const userId = this.state.lotsSelection[radioInputName] || currentRoundBidding.choiceLotsSelectionMap.get(lotId);\n if (userId) {\n lotsIds.push(lotId);\n usersIds.push(userId);\n }\n });\n\n _logger.debug('_computeSelectionLotsIdsAndUsersIdsFromState: arrays ', lotsIds, usersIds);\n return { lotsIds, usersIds };\n }\n\n handleClick_SubmitAndReopenChoiceButton = () => {\n const { lotsIds, usersIds } = this._computeSelectionLotsIdsAndUsersIdsFromState();\n AuctionsManager.currentWebcastAuctionHandler.controller.sendChoiceLotsAssignment(this.props.currentRoundBidding.roundId, lotsIds, usersIds, RoundTypeEnum.GROUP_CHOICE_REOPEN);\n };\n\n handleClick_SubmitAndStartNewRoundButton = () => {\n const { lotsIds, usersIds } = this._computeSelectionLotsIdsAndUsersIdsFromState();\n AuctionsManager.currentWebcastAuctionHandler.controller.sendChoiceLotsAssignment(this.props.currentRoundBidding.roundId, lotsIds, usersIds, RoundTypeEnum.GROUP_CHOICE);\n };\n\n handleClick_CancelButton = () => {\n AuctionsManager.currentWebcastAuctionHandler.controller.sendRoundStop(this.props.currentRoundBidding.roundId, RoundStopTypeEnum.CANCEL);\n };\n\n\n\n\n\n renderChoiceLotListItem = (lotId:number, hasInternetBidder:boolean, winnerBidderUserId:number, highestBid:Bid) => {\n const currentRoundBidding:ReduxWebcastCurrentRoundBiddingType = this.props.currentRoundBidding;\n const lot:Lot = this.props.auctionData.lotsMapById.get(lotId);\n const radioInputName = `lot_${lotId}`;\n\n const bidderUserId:number = winnerBidderUserId > 0 ? winnerBidderUserId : currentRoundBidding.choiceLotsSelectionMap.get(lotId);\n const bidderDisplay:string = bidderUserId > 0 ? (this.props.participantsByUserId.get(bidderUserId) || highestBid || { bidderDisplay: '[bidder]' }).bidderDisplay : '[internet bidder]';\n\n const isBidderChecked = bidderUserId && this.isLotInputRadioChecked(lotId, bidderUserId);\n const isFloorChecked = this.isLotInputRadioChecked(lotId, this.clerkUserId);\n const isNoneChecked = ! (isBidderChecked || isFloorChecked);\n\n\n\n return (\n
\n
\n {lot.number}\n {lot.name}\n\n {\n currentRoundBidding.choiceLotsSelectionMap && currentRoundBidding.choiceLotsSelectionMap.get(lot.id)\n && {'\\u27F9'}\n }\n
\n
\n {\n hasInternetBidder && (\n bidderUserId > 0\n ? \n : \n )\n }\n \n \n
\n
\n )\n };\n\n\n\n render() {\n _logger.debug('.render() props:', this.props, ' state:', this.state);\n\n const highestBid:Bid = this.props.currentRoundBidding.highestBid;\n // for CHOICE_REOPEN, we consider the winner=false\n const winnerUserId = this.props.currentRound.roundType === RoundTypeEnum.GROUP_CHOICE_REOPEN ? false : highestBid.userId;\n const internetBidderUserId = (winnerUserId !== false) && (winnerUserId !== this.clerkUserId) ? winnerUserId : 0;\n const hasInternetBidder:boolean = (winnerUserId === false) || (winnerUserId !== this.clerkUserId);\n\n return (\n
\n
\n

Assign Lots

\n
\n {\n hasInternetBidder &&\n (internetBidderUserId > 0\n ? \n : Bidder\n )\n }\n \n \n
\n
\n
\n
\n {this.props.currentRound.lotsIds.map(lotId => this.renderChoiceLotListItem(lotId, hasInternetBidder, internetBidderUserId, highestBid))}\n
\n
\n
\n \n \n \n
\n
\n );\n }\n}\n\nexport default connect(({ activeWebcast }: {activeWebcast:ReduxActiveWebcastSubStateType}) => {\n return {\n auctionData: activeWebcast.webcastAuctionData,\n participantsByUserId: activeWebcast.webcastParticipants.mapByUserId,\n };\n})(ClerkRoundChoiceLotsSelectConfirmCmp);\n\n\n", "import React from \"react\";\nimport {connect} from \"react-redux\";\nimport ClerkRoundStartSetOpeningBidCmp from \"./ClerkRoundStartSetOpeningBidCmp\";\nimport ClerkRoundStartUpdateOpeningBidCmp from \"./ClerkRoundStartUpdateOpeningBidCmp\";\nimport ClerkRoundBiddingWithBidsReceivedCmp from \"./ClerkRoundBiddingWithBidsReceivedCmp\";\nimport ClerkRoundStopInfoCmp from \"./ClerkRoundStopInfoCmp\";\nimport ClerkRoundChoiceLotsSelectConfirmCmp from \"./ClerkRoundChoiceLotsSelectConfirmCmp\";\nimport {ReduxActiveWebcastSubStateType} from \"@nextlot/core/webcast/redux/reducerActiveWebcast\";\nimport {ReduxWebcastCurrentRoundType} from \"@nextlot/core/webcast/redux/webcast/reducerWebcastCurrentRound\";\nimport {ReduxWebcastCurrentRoundBiddingType} from \"@nextlot/core/webcast/redux/webcast/reducerWebcastCurrentRoundBidding\";\nimport {WebcastStateEnum} from \"@nextlot/core/webcast/data/WebcastDataDomain\";\n\n\ntype RootCmpPropsType = {\n webcastStatusState: number,\n webcastStatusPaused: boolean,\n currentRound: ReduxWebcastCurrentRoundType,\n currentRoundBidding: ReduxWebcastCurrentRoundBiddingType,\n};\n\n\n\nfunction renderContent(props:RootCmpPropsType) {\n if (props.webcastStatusState === WebcastStateEnum.WEBCAST_STATE__ROUND_STOPPING_TRANSITIONAL) {\n // round is stopping\n return \n }\n else if (props.webcastStatusState === WebcastStateEnum.WEBCAST_STATE__DURING_ROUND_BIDDING) {\n\n if (props.currentRoundBidding.highestBid) {\n // we have bids!\n return \n }\n else if (props.currentRoundBidding.askingBidValue) {\n // we're looking for an opening + first bid\n return \n }\n else {\n // should NEVER get here!\n return

Invalid state! (CBA#48)

\n }\n }\n else if (props.webcastStatusState === WebcastStateEnum.WEBCAST_STATE__CHOICE_ROUND_LOTS_SELECT) {\n // Choice round: select lots\n return \n }\n else {\n // BETWEEN_ROUNDS: no asking bid, and no bids placed\n // => we're about to start the round\n return \n }\n}\n\n\nfunction renderPauseOverlay(paused:boolean) {\n if (! paused) {\n return null;\n }\n\n return (\n
\n

Event paused

\n
\n )\n}\n\n\n\nfunction ClerkBiddingAreaLayoutRootCmp(props:RootCmpPropsType) {\n return (\n \n {renderPauseOverlay(props.webcastStatusPaused)}\n {renderContent(props)}\n \n )\n}\n\n\n\nexport default connect(({ activeWebcast }: {activeWebcast:ReduxActiveWebcastSubStateType}) => {\n return {\n webcastStatusState: activeWebcast.webcastStatus.state,\n webcastStatusPaused: activeWebcast.webcastStatus.paused,\n currentRound: activeWebcast.webcastCurrentRound,\n currentRoundBidding: activeWebcast.webcastCurrentRoundBidding,\n };\n})(ClerkBiddingAreaLayoutRootCmp);\n\n\n", "var safeIsNaN = Number.isNaN ||\n function ponyfill(value) {\n return typeof value === 'number' && value !== value;\n };\nfunction isEqual(first, second) {\n if (first === second) {\n return true;\n }\n if (safeIsNaN(first) && safeIsNaN(second)) {\n return true;\n }\n return false;\n}\nfunction areInputsEqual(newInputs, lastInputs) {\n if (newInputs.length !== lastInputs.length) {\n return false;\n }\n for (var i = 0; i < newInputs.length; i++) {\n if (!isEqual(newInputs[i], lastInputs[i])) {\n return false;\n }\n }\n return true;\n}\n\nfunction memoizeOne(resultFn, isEqual) {\n if (isEqual === void 0) { isEqual = areInputsEqual; }\n var cache = null;\n function memoized() {\n var newArgs = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n newArgs[_i] = arguments[_i];\n }\n if (cache && cache.lastThis === this && isEqual(newArgs, cache.lastArgs)) {\n return cache.lastResult;\n }\n var lastResult = resultFn.apply(this, newArgs);\n cache = {\n lastResult: lastResult,\n lastArgs: newArgs,\n lastThis: this,\n };\n return lastResult;\n }\n memoized.clear = function clear() {\n cache = null;\n };\n return memoized;\n}\n\nexport { memoizeOne as default };\n", "import { Component, createElement } from 'react';\n\n/**\n * Detect Element Resize.\n * https://github.com/sdecima/javascript-detect-element-resize\n * Sebastian Decima\n *\n * Forked from version 0.5.3; includes the following modifications:\n * 1) Guard against unsafe 'window' and 'document' references (to support SSR).\n * 2) Defer initialization code via a top-level function wrapper (to support SSR).\n * 3) Avoid unnecessary reflows by not measuring size for scroll events bubbling from children.\n * 4) Add nonce for style element.\n * 5) Use 'export' statement over 'module.exports' assignment\n **/\n\n// Check `document` and `window` in case of server-side rendering\nlet windowObject;\nif (typeof window !== \"undefined\") {\n windowObject = window;\n\n // eslint-disable-next-line no-restricted-globals\n} else if (typeof self !== \"undefined\") {\n // eslint-disable-next-line no-restricted-globals\n windowObject = self;\n} else {\n windowObject = global;\n}\nlet cancelFrame = null;\nlet requestFrame = null;\nconst TIMEOUT_DURATION = 20;\nconst clearTimeoutFn = windowObject.clearTimeout;\nconst setTimeoutFn = windowObject.setTimeout;\nconst cancelAnimationFrameFn = windowObject.cancelAnimationFrame || windowObject.mozCancelAnimationFrame || windowObject.webkitCancelAnimationFrame;\nconst requestAnimationFrameFn = windowObject.requestAnimationFrame || windowObject.mozRequestAnimationFrame || windowObject.webkitRequestAnimationFrame;\nif (cancelAnimationFrameFn == null || requestAnimationFrameFn == null) {\n // For environments that don't support animation frame,\n // fallback to a setTimeout based approach.\n cancelFrame = clearTimeoutFn;\n requestFrame = function requestAnimationFrameViaSetTimeout(callback) {\n return setTimeoutFn(callback, TIMEOUT_DURATION);\n };\n} else {\n // Counter intuitively, environments that support animation frames can be trickier.\n // Chrome's \"Throttle non-visible cross-origin iframes\" flag can prevent rAFs from being called.\n // In this case, we should fallback to a setTimeout() implementation.\n cancelFrame = function cancelFrame([animationFrameID, timeoutID]) {\n cancelAnimationFrameFn(animationFrameID);\n clearTimeoutFn(timeoutID);\n };\n requestFrame = function requestAnimationFrameWithSetTimeoutFallback(callback) {\n const animationFrameID = requestAnimationFrameFn(function animationFrameCallback() {\n clearTimeoutFn(timeoutID);\n callback();\n });\n const timeoutID = setTimeoutFn(function timeoutCallback() {\n cancelAnimationFrameFn(animationFrameID);\n callback();\n }, TIMEOUT_DURATION);\n return [animationFrameID, timeoutID];\n };\n}\nfunction createDetectElementResize(nonce) {\n let animationKeyframes;\n let animationName;\n let animationStartEvent;\n let animationStyle;\n let checkTriggers;\n let resetTriggers;\n let scrollListener;\n const attachEvent = typeof document !== \"undefined\" && document.attachEvent;\n if (!attachEvent) {\n resetTriggers = function (element) {\n const triggers = element.__resizeTriggers__,\n expand = triggers.firstElementChild,\n contract = triggers.lastElementChild,\n expandChild = expand.firstElementChild;\n contract.scrollLeft = contract.scrollWidth;\n contract.scrollTop = contract.scrollHeight;\n expandChild.style.width = expand.offsetWidth + 1 + \"px\";\n expandChild.style.height = expand.offsetHeight + 1 + \"px\";\n expand.scrollLeft = expand.scrollWidth;\n expand.scrollTop = expand.scrollHeight;\n };\n checkTriggers = function (element) {\n return element.offsetWidth !== element.__resizeLast__.width || element.offsetHeight !== element.__resizeLast__.height;\n };\n scrollListener = function (e) {\n // Don't measure (which forces) reflow for scrolls that happen inside of children!\n if (e.target.className && typeof e.target.className.indexOf === \"function\" && e.target.className.indexOf(\"contract-trigger\") < 0 && e.target.className.indexOf(\"expand-trigger\") < 0) {\n return;\n }\n const element = this;\n resetTriggers(this);\n if (this.__resizeRAF__) {\n cancelFrame(this.__resizeRAF__);\n }\n this.__resizeRAF__ = requestFrame(function animationFrame() {\n if (checkTriggers(element)) {\n element.__resizeLast__.width = element.offsetWidth;\n element.__resizeLast__.height = element.offsetHeight;\n element.__resizeListeners__.forEach(function forEachResizeListener(fn) {\n fn.call(element, e);\n });\n }\n });\n };\n\n /* Detect CSS Animations support to detect element display/re-attach */\n let animation = false;\n let keyframeprefix = \"\";\n animationStartEvent = \"animationstart\";\n const domPrefixes = \"Webkit Moz O ms\".split(\" \");\n let startEvents = \"webkitAnimationStart animationstart oAnimationStart MSAnimationStart\".split(\" \");\n let pfx = \"\";\n {\n const elm = document.createElement(\"fakeelement\");\n if (elm.style.animationName !== undefined) {\n animation = true;\n }\n if (animation === false) {\n for (let i = 0; i < domPrefixes.length; i++) {\n if (elm.style[domPrefixes[i] + \"AnimationName\"] !== undefined) {\n pfx = domPrefixes[i];\n keyframeprefix = \"-\" + pfx.toLowerCase() + \"-\";\n animationStartEvent = startEvents[i];\n animation = true;\n break;\n }\n }\n }\n }\n animationName = \"resizeanim\";\n animationKeyframes = \"@\" + keyframeprefix + \"keyframes \" + animationName + \" { from { opacity: 0; } to { opacity: 0; } } \";\n animationStyle = keyframeprefix + \"animation: 1ms \" + animationName + \"; \";\n }\n const createStyles = function (doc) {\n if (!doc.getElementById(\"detectElementResize\")) {\n //opacity:0 works around a chrome bug https://code.google.com/p/chromium/issues/detail?id=286360\n const css = (animationKeyframes ? animationKeyframes : \"\") + \".resize-triggers { \" + (animationStyle ? animationStyle : \"\") + \"visibility: hidden; opacity: 0; } \" + '.resize-triggers, .resize-triggers > div, .contract-trigger:before { content: \" \"; display: block; position: absolute; top: 0; left: 0; height: 100%; width: 100%; overflow: hidden; z-index: -1; } .resize-triggers > div { background: #eee; overflow: auto; } .contract-trigger:before { width: 200%; height: 200%; }',\n head = doc.head || doc.getElementsByTagName(\"head\")[0],\n style = doc.createElement(\"style\");\n style.id = \"detectElementResize\";\n style.type = \"text/css\";\n if (nonce != null) {\n style.setAttribute(\"nonce\", nonce);\n }\n if (style.styleSheet) {\n style.styleSheet.cssText = css;\n } else {\n style.appendChild(doc.createTextNode(css));\n }\n head.appendChild(style);\n }\n };\n const addResizeListener = function (element, fn) {\n if (attachEvent) {\n element.attachEvent(\"onresize\", fn);\n } else {\n if (!element.__resizeTriggers__) {\n const doc = element.ownerDocument;\n const elementStyle = windowObject.getComputedStyle(element);\n if (elementStyle && elementStyle.position === \"static\") {\n element.style.position = \"relative\";\n }\n createStyles(doc);\n element.__resizeLast__ = {};\n element.__resizeListeners__ = [];\n (element.__resizeTriggers__ = doc.createElement(\"div\")).className = \"resize-triggers\";\n const expandTrigger = doc.createElement(\"div\");\n expandTrigger.className = \"expand-trigger\";\n expandTrigger.appendChild(doc.createElement(\"div\"));\n const contractTrigger = doc.createElement(\"div\");\n contractTrigger.className = \"contract-trigger\";\n element.__resizeTriggers__.appendChild(expandTrigger);\n element.__resizeTriggers__.appendChild(contractTrigger);\n element.appendChild(element.__resizeTriggers__);\n resetTriggers(element);\n element.addEventListener(\"scroll\", scrollListener, true);\n\n /* Listen for a css animation to detect element display/re-attach */\n if (animationStartEvent) {\n element.__resizeTriggers__.__animationListener__ = function animationListener(e) {\n if (e.animationName === animationName) {\n resetTriggers(element);\n }\n };\n element.__resizeTriggers__.addEventListener(animationStartEvent, element.__resizeTriggers__.__animationListener__);\n }\n }\n element.__resizeListeners__.push(fn);\n }\n };\n const removeResizeListener = function (element, fn) {\n if (attachEvent) {\n element.detachEvent(\"onresize\", fn);\n } else {\n element.__resizeListeners__.splice(element.__resizeListeners__.indexOf(fn), 1);\n if (!element.__resizeListeners__.length) {\n element.removeEventListener(\"scroll\", scrollListener, true);\n if (element.__resizeTriggers__.__animationListener__) {\n element.__resizeTriggers__.removeEventListener(animationStartEvent, element.__resizeTriggers__.__animationListener__);\n element.__resizeTriggers__.__animationListener__ = null;\n }\n try {\n element.__resizeTriggers__ = !element.removeChild(element.__resizeTriggers__);\n } catch (e) {\n // Preact compat; see developit/preact-compat/issues/228\n }\n }\n }\n };\n return {\n addResizeListener,\n removeResizeListener\n };\n}\n\nclass AutoSizer extends Component {\n constructor(...args) {\n super(...args);\n this.state = {\n height: this.props.defaultHeight || 0,\n scaledHeight: this.props.defaultHeight || 0,\n scaledWidth: this.props.defaultWidth || 0,\n width: this.props.defaultWidth || 0\n };\n this._autoSizer = null;\n this._detectElementResize = null;\n this._parentNode = null;\n this._resizeObserver = null;\n this._timeoutId = null;\n this._onResize = () => {\n this._timeoutId = null;\n const {\n disableHeight,\n disableWidth,\n onResize\n } = this.props;\n if (this._parentNode) {\n // Guard against AutoSizer component being removed from the DOM immediately after being added.\n // This can result in invalid style values which can result in NaN values if we don't handle them.\n // See issue #150 for more context.\n\n const style = window.getComputedStyle(this._parentNode) || {};\n const paddingLeft = parseFloat(style.paddingLeft || \"0\");\n const paddingRight = parseFloat(style.paddingRight || \"0\");\n const paddingTop = parseFloat(style.paddingTop || \"0\");\n const paddingBottom = parseFloat(style.paddingBottom || \"0\");\n const rect = this._parentNode.getBoundingClientRect();\n const scaledHeight = rect.height - paddingTop - paddingBottom;\n const scaledWidth = rect.width - paddingLeft - paddingRight;\n const height = this._parentNode.offsetHeight - paddingTop - paddingBottom;\n const width = this._parentNode.offsetWidth - paddingLeft - paddingRight;\n if (!disableHeight && (this.state.height !== height || this.state.scaledHeight !== scaledHeight) || !disableWidth && (this.state.width !== width || this.state.scaledWidth !== scaledWidth)) {\n this.setState({\n height,\n width,\n scaledHeight,\n scaledWidth\n });\n if (typeof onResize === \"function\") {\n onResize({\n height,\n scaledHeight,\n scaledWidth,\n width\n });\n }\n }\n }\n };\n this._setRef = autoSizer => {\n this._autoSizer = autoSizer;\n };\n }\n componentDidMount() {\n const {\n nonce\n } = this.props;\n const parentNode = this._autoSizer ? this._autoSizer.parentNode : null;\n if (parentNode != null && parentNode.ownerDocument && parentNode.ownerDocument.defaultView && parentNode instanceof parentNode.ownerDocument.defaultView.HTMLElement) {\n // Delay access of parentNode until mount.\n // This handles edge-cases where the component has already been unmounted before its ref has been set,\n // As well as libraries like react-lite which have a slightly different lifecycle.\n this._parentNode = parentNode;\n\n // Use ResizeObserver from the same context where parentNode (which we will observe) was defined\n // Using just global can result into onResize events not being emitted in cases with multiple realms\n const ResizeObserverInstance = parentNode.ownerDocument.defaultView.ResizeObserver;\n if (ResizeObserverInstance != null) {\n this._resizeObserver = new ResizeObserverInstance(() => {\n // Guard against \"ResizeObserver loop limit exceeded\" error;\n // could be triggered if the state update causes the ResizeObserver handler to run long.\n // See https://github.com/bvaughn/react-virtualized-auto-sizer/issues/55\n this._timeoutId = setTimeout(this._onResize, 0);\n });\n this._resizeObserver.observe(parentNode);\n } else {\n // Defer requiring resize handler in order to support server-side rendering.\n // See issue #41\n this._detectElementResize = createDetectElementResize(nonce);\n this._detectElementResize.addResizeListener(parentNode, this._onResize);\n }\n this._onResize();\n }\n }\n componentWillUnmount() {\n if (this._parentNode) {\n if (this._detectElementResize) {\n this._detectElementResize.removeResizeListener(this._parentNode, this._onResize);\n }\n if (this._timeoutId !== null) {\n clearTimeout(this._timeoutId);\n }\n if (this._resizeObserver) {\n this._resizeObserver.disconnect();\n }\n }\n }\n render() {\n const {\n children,\n defaultHeight,\n defaultWidth,\n disableHeight = false,\n disableWidth = false,\n doNotBailOutOnEmptyChildren = false,\n nonce,\n onResize,\n style = {},\n tagName = \"div\",\n ...rest\n } = this.props;\n const {\n height,\n scaledHeight,\n scaledWidth,\n width\n } = this.state;\n\n // Outer div should not force width/height since that may prevent containers from shrinking.\n // Inner component should overflow and use calculated width/height.\n // See issue #68 for more information.\n const outerStyle = {\n overflow: \"visible\"\n };\n const childParams = {};\n\n // Avoid rendering children before the initial measurements have been collected.\n // At best this would just be wasting cycles.\n let bailoutOnChildren = false;\n if (!disableHeight) {\n if (height === 0) {\n bailoutOnChildren = true;\n }\n outerStyle.height = 0;\n childParams.height = height;\n childParams.scaledHeight = scaledHeight;\n }\n if (!disableWidth) {\n if (width === 0) {\n bailoutOnChildren = true;\n }\n outerStyle.width = 0;\n childParams.width = width;\n childParams.scaledWidth = scaledWidth;\n }\n if (doNotBailOutOnEmptyChildren) {\n bailoutOnChildren = false;\n }\n return createElement(tagName, {\n ref: this._setRef,\n style: {\n ...outerStyle,\n ...style\n },\n ...rest\n }, !bailoutOnChildren && children(childParams));\n }\n}\n\nfunction isHeightAndWidthProps(props) {\n return props && props.disableHeight !== true && props.disableWidth !== true;\n}\nfunction isHeightOnlyProps(props) {\n return props && props.disableHeight !== true && props.disableWidth === true;\n}\nfunction isWidthOnlyProps(props) {\n return props && props.disableHeight === true && props.disableWidth !== true;\n}\n\nexport { AutoSizer as default, isHeightAndWidthProps, isHeightOnlyProps, isWidthOnlyProps };\n", "export default function _extends() {\n _extends = Object.assign ? Object.assign.bind() : function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n return target;\n };\n return _extends.apply(this, arguments);\n}", "export default function _assertThisInitialized(self) {\n if (self === void 0) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n return self;\n}", "export default function _setPrototypeOf(o, p) {\n _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {\n o.__proto__ = p;\n return o;\n };\n return _setPrototypeOf(o, p);\n}", "import setPrototypeOf from \"./setPrototypeOf.js\";\nexport default function _inheritsLoose(subClass, superClass) {\n subClass.prototype = Object.create(superClass.prototype);\n subClass.prototype.constructor = subClass;\n setPrototypeOf(subClass, superClass);\n}", "var safeIsNaN = Number.isNaN ||\n function ponyfill(value) {\n return typeof value === 'number' && value !== value;\n };\nfunction isEqual(first, second) {\n if (first === second) {\n return true;\n }\n if (safeIsNaN(first) && safeIsNaN(second)) {\n return true;\n }\n return false;\n}\nfunction areInputsEqual(newInputs, lastInputs) {\n if (newInputs.length !== lastInputs.length) {\n return false;\n }\n for (var i = 0; i < newInputs.length; i++) {\n if (!isEqual(newInputs[i], lastInputs[i])) {\n return false;\n }\n }\n return true;\n}\n\nfunction memoizeOne(resultFn, isEqual) {\n if (isEqual === void 0) { isEqual = areInputsEqual; }\n var lastThis;\n var lastArgs = [];\n var lastResult;\n var calledOnce = false;\n function memoized() {\n var newArgs = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n newArgs[_i] = arguments[_i];\n }\n if (calledOnce && lastThis === this && isEqual(newArgs, lastArgs)) {\n return lastResult;\n }\n lastResult = resultFn.apply(this, newArgs);\n calledOnce = true;\n lastThis = this;\n lastArgs = newArgs;\n return lastResult;\n }\n return memoized;\n}\n\nexport default memoizeOne;\n", "export default function _objectWithoutPropertiesLoose(source, excluded) {\n if (source == null) return {};\n var target = {};\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n if (excluded.indexOf(key) >= 0) continue;\n target[key] = source[key];\n }\n }\n return target;\n}", "// @flow\n\n// Animation frame based implementation of setTimeout.\n// Inspired by Joe Lambert, https://gist.github.com/joelambert/1002116#file-requesttimeout-js\n\nconst hasNativePerformanceNow =\n typeof performance === 'object' && typeof performance.now === 'function';\n\nconst now = hasNativePerformanceNow\n ? () => performance.now()\n : () => Date.now();\n\nexport type TimeoutID = {|\n id: AnimationFrameID,\n|};\n\nexport function cancelTimeout(timeoutID: TimeoutID) {\n cancelAnimationFrame(timeoutID.id);\n}\n\nexport function requestTimeout(callback: Function, delay: number): TimeoutID {\n const start = now();\n\n function tick() {\n if (now() - start >= delay) {\n callback.call(null);\n } else {\n timeoutID.id = requestAnimationFrame(tick);\n }\n }\n\n const timeoutID: TimeoutID = {\n id: requestAnimationFrame(tick),\n };\n\n return timeoutID;\n}\n", "// @flow\n\nlet size: number = -1;\n\n// This utility copied from \"dom-helpers\" package.\nexport function getScrollbarSize(recalculate?: boolean = false): number {\n if (size === -1 || recalculate) {\n const div = document.createElement('div');\n const style = div.style;\n style.width = '50px';\n style.height = '50px';\n style.overflow = 'scroll';\n\n ((document.body: any): HTMLBodyElement).appendChild(div);\n\n size = div.offsetWidth - div.clientWidth;\n\n ((document.body: any): HTMLBodyElement).removeChild(div);\n }\n\n return size;\n}\n\nexport type RTLOffsetType =\n | 'negative'\n | 'positive-descending'\n | 'positive-ascending';\n\nlet cachedRTLResult: RTLOffsetType | null = null;\n\n// TRICKY According to the spec, scrollLeft should be negative for RTL aligned elements.\n// Chrome does not seem to adhere; its scrollLeft values are positive (measured relative to the left).\n// Safari's elastic bounce makes detecting this even more complicated wrt potential false positives.\n// The safest way to check this is to intentionally set a negative offset,\n// and then verify that the subsequent \"scroll\" event matches the negative offset.\n// If it does not match, then we can assume a non-standard RTL scroll implementation.\nexport function getRTLOffsetType(recalculate?: boolean = false): RTLOffsetType {\n if (cachedRTLResult === null || recalculate) {\n const outerDiv = document.createElement('div');\n const outerStyle = outerDiv.style;\n outerStyle.width = '50px';\n outerStyle.height = '50px';\n outerStyle.overflow = 'scroll';\n outerStyle.direction = 'rtl';\n\n const innerDiv = document.createElement('div');\n const innerStyle = innerDiv.style;\n innerStyle.width = '100px';\n innerStyle.height = '100px';\n\n outerDiv.appendChild(innerDiv);\n\n ((document.body: any): HTMLBodyElement).appendChild(outerDiv);\n\n if (outerDiv.scrollLeft > 0) {\n cachedRTLResult = 'positive-descending';\n } else {\n outerDiv.scrollLeft = 1;\n if (outerDiv.scrollLeft === 0) {\n cachedRTLResult = 'negative';\n } else {\n cachedRTLResult = 'positive-ascending';\n }\n }\n\n ((document.body: any): HTMLBodyElement).removeChild(outerDiv);\n\n return cachedRTLResult;\n }\n\n return cachedRTLResult;\n}\n", "// @flow\n\nimport memoizeOne from 'memoize-one';\nimport { createElement, PureComponent } from 'react';\nimport { cancelTimeout, requestTimeout } from './timer';\nimport { getScrollbarSize, getRTLOffsetType } from './domHelpers';\n\nimport type { TimeoutID } from './timer';\n\ntype Direction = 'ltr' | 'rtl';\nexport type ScrollToAlign = 'auto' | 'smart' | 'center' | 'start' | 'end';\n\ntype itemSize = number | ((index: number) => number);\n\ntype RenderComponentProps = {|\n columnIndex: number,\n data: T,\n isScrolling?: boolean,\n rowIndex: number,\n style: Object,\n|};\nexport type RenderComponent = React$ComponentType<\n $Shape>\n>;\n\ntype ScrollDirection = 'forward' | 'backward';\n\ntype OnItemsRenderedCallback = ({\n overscanColumnStartIndex: number,\n overscanColumnStopIndex: number,\n overscanRowStartIndex: number,\n overscanRowStopIndex: number,\n visibleColumnStartIndex: number,\n visibleColumnStopIndex: number,\n visibleRowStartIndex: number,\n visibleRowStopIndex: number,\n}) => void;\ntype OnScrollCallback = ({\n horizontalScrollDirection: ScrollDirection,\n scrollLeft: number,\n scrollTop: number,\n scrollUpdateWasRequested: boolean,\n verticalScrollDirection: ScrollDirection,\n}) => void;\n\ntype ScrollEvent = SyntheticEvent;\ntype ItemStyleCache = { [key: string]: Object };\n\ntype OuterProps = {|\n children: React$Node,\n className: string | void,\n onScroll: ScrollEvent => void,\n style: {\n [string]: mixed,\n },\n|};\n\ntype InnerProps = {|\n children: React$Node,\n style: {\n [string]: mixed,\n },\n|};\n\nexport type Props = {|\n children: RenderComponent,\n className?: string,\n columnCount: number,\n columnWidth: itemSize,\n direction: Direction,\n height: number,\n initialScrollLeft?: number,\n initialScrollTop?: number,\n innerRef?: any,\n innerElementType?: string | React$AbstractComponent,\n innerTagName?: string, // deprecated\n itemData: T,\n itemKey?: (params: {|\n columnIndex: number,\n data: T,\n rowIndex: number,\n |}) => any,\n onItemsRendered?: OnItemsRenderedCallback,\n onScroll?: OnScrollCallback,\n outerRef?: any,\n outerElementType?: string | React$AbstractComponent,\n outerTagName?: string, // deprecated\n overscanColumnCount?: number,\n overscanColumnsCount?: number, // deprecated\n overscanCount?: number, // deprecated\n overscanRowCount?: number,\n overscanRowsCount?: number, // deprecated\n rowCount: number,\n rowHeight: itemSize,\n style?: Object,\n useIsScrolling: boolean,\n width: number,\n|};\n\ntype State = {|\n instance: any,\n isScrolling: boolean,\n horizontalScrollDirection: ScrollDirection,\n scrollLeft: number,\n scrollTop: number,\n scrollUpdateWasRequested: boolean,\n verticalScrollDirection: ScrollDirection,\n|};\n\ntype getItemOffset = (\n props: Props,\n index: number,\n instanceProps: any\n) => number;\ntype getItemSize = (\n props: Props,\n index: number,\n instanceProps: any\n) => number;\ntype getEstimatedTotalSize = (props: Props, instanceProps: any) => number;\ntype GetOffsetForItemAndAlignment = (\n props: Props,\n index: number,\n align: ScrollToAlign,\n scrollOffset: number,\n instanceProps: any,\n scrollbarSize: number\n) => number;\ntype GetStartIndexForOffset = (\n props: Props,\n offset: number,\n instanceProps: any\n) => number;\ntype GetStopIndexForStartIndex = (\n props: Props,\n startIndex: number,\n scrollOffset: number,\n instanceProps: any\n) => number;\ntype InitInstanceProps = (props: Props, instance: any) => any;\ntype ValidateProps = (props: Props) => void;\n\nconst IS_SCROLLING_DEBOUNCE_INTERVAL = 150;\n\nconst defaultItemKey = ({ columnIndex, data, rowIndex }) =>\n `${rowIndex}:${columnIndex}`;\n\n// In DEV mode, this Set helps us only log a warning once per component instance.\n// This avoids spamming the console every time a render happens.\nlet devWarningsOverscanCount = null;\nlet devWarningsOverscanRowsColumnsCount = null;\nlet devWarningsTagName = null;\nif (process.env.NODE_ENV !== 'production') {\n if (typeof window !== 'undefined' && typeof window.WeakSet !== 'undefined') {\n devWarningsOverscanCount = new WeakSet();\n devWarningsOverscanRowsColumnsCount = new WeakSet();\n devWarningsTagName = new WeakSet();\n }\n}\n\nexport default function createGridComponent({\n getColumnOffset,\n getColumnStartIndexForOffset,\n getColumnStopIndexForStartIndex,\n getColumnWidth,\n getEstimatedTotalHeight,\n getEstimatedTotalWidth,\n getOffsetForColumnAndAlignment,\n getOffsetForRowAndAlignment,\n getRowHeight,\n getRowOffset,\n getRowStartIndexForOffset,\n getRowStopIndexForStartIndex,\n initInstanceProps,\n shouldResetStyleCacheOnItemSizeChange,\n validateProps,\n}: {|\n getColumnOffset: getItemOffset,\n getColumnStartIndexForOffset: GetStartIndexForOffset,\n getColumnStopIndexForStartIndex: GetStopIndexForStartIndex,\n getColumnWidth: getItemSize,\n getEstimatedTotalHeight: getEstimatedTotalSize,\n getEstimatedTotalWidth: getEstimatedTotalSize,\n getOffsetForColumnAndAlignment: GetOffsetForItemAndAlignment,\n getOffsetForRowAndAlignment: GetOffsetForItemAndAlignment,\n getRowOffset: getItemOffset,\n getRowHeight: getItemSize,\n getRowStartIndexForOffset: GetStartIndexForOffset,\n getRowStopIndexForStartIndex: GetStopIndexForStartIndex,\n initInstanceProps: InitInstanceProps,\n shouldResetStyleCacheOnItemSizeChange: boolean,\n validateProps: ValidateProps,\n|}) {\n return class Grid extends PureComponent, State> {\n _instanceProps: any = initInstanceProps(this.props, this);\n _resetIsScrollingTimeoutId: TimeoutID | null = null;\n _outerRef: ?HTMLDivElement;\n\n static defaultProps = {\n direction: 'ltr',\n itemData: undefined,\n useIsScrolling: false,\n };\n\n state: State = {\n instance: this,\n isScrolling: false,\n horizontalScrollDirection: 'forward',\n scrollLeft:\n typeof this.props.initialScrollLeft === 'number'\n ? this.props.initialScrollLeft\n : 0,\n scrollTop:\n typeof this.props.initialScrollTop === 'number'\n ? this.props.initialScrollTop\n : 0,\n scrollUpdateWasRequested: false,\n verticalScrollDirection: 'forward',\n };\n\n // Always use explicit constructor for React components.\n // It produces less code after transpilation. (#26)\n // eslint-disable-next-line no-useless-constructor\n constructor(props: Props) {\n super(props);\n }\n\n static getDerivedStateFromProps(\n nextProps: Props,\n prevState: State\n ): $Shape | null {\n validateSharedProps(nextProps, prevState);\n validateProps(nextProps);\n return null;\n }\n\n scrollTo({\n scrollLeft,\n scrollTop,\n }: {\n scrollLeft: number,\n scrollTop: number,\n }): void {\n if (scrollLeft !== undefined) {\n scrollLeft = Math.max(0, scrollLeft);\n }\n if (scrollTop !== undefined) {\n scrollTop = Math.max(0, scrollTop);\n }\n\n this.setState(prevState => {\n if (scrollLeft === undefined) {\n scrollLeft = prevState.scrollLeft;\n }\n if (scrollTop === undefined) {\n scrollTop = prevState.scrollTop;\n }\n\n if (\n prevState.scrollLeft === scrollLeft &&\n prevState.scrollTop === scrollTop\n ) {\n return null;\n }\n\n return {\n horizontalScrollDirection:\n prevState.scrollLeft < scrollLeft ? 'forward' : 'backward',\n scrollLeft: scrollLeft,\n scrollTop: scrollTop,\n scrollUpdateWasRequested: true,\n verticalScrollDirection:\n prevState.scrollTop < scrollTop ? 'forward' : 'backward',\n };\n }, this._resetIsScrollingDebounced);\n }\n\n scrollToItem({\n align = 'auto',\n columnIndex,\n rowIndex,\n }: {\n align: ScrollToAlign,\n columnIndex?: number,\n rowIndex?: number,\n }): void {\n const { columnCount, height, rowCount, width } = this.props;\n const { scrollLeft, scrollTop } = this.state;\n const scrollbarSize = getScrollbarSize();\n\n if (columnIndex !== undefined) {\n columnIndex = Math.max(0, Math.min(columnIndex, columnCount - 1));\n }\n if (rowIndex !== undefined) {\n rowIndex = Math.max(0, Math.min(rowIndex, rowCount - 1));\n }\n\n const estimatedTotalHeight = getEstimatedTotalHeight(\n this.props,\n this._instanceProps\n );\n const estimatedTotalWidth = getEstimatedTotalWidth(\n this.props,\n this._instanceProps\n );\n\n // The scrollbar size should be considered when scrolling an item into view,\n // to ensure it's fully visible.\n // But we only need to account for its size when it's actually visible.\n const horizontalScrollbarSize =\n estimatedTotalWidth > width ? scrollbarSize : 0;\n const verticalScrollbarSize =\n estimatedTotalHeight > height ? scrollbarSize : 0;\n\n this.scrollTo({\n scrollLeft:\n columnIndex !== undefined\n ? getOffsetForColumnAndAlignment(\n this.props,\n columnIndex,\n align,\n scrollLeft,\n this._instanceProps,\n verticalScrollbarSize\n )\n : scrollLeft,\n scrollTop:\n rowIndex !== undefined\n ? getOffsetForRowAndAlignment(\n this.props,\n rowIndex,\n align,\n scrollTop,\n this._instanceProps,\n horizontalScrollbarSize\n )\n : scrollTop,\n });\n }\n\n componentDidMount() {\n const { initialScrollLeft, initialScrollTop } = this.props;\n\n if (this._outerRef != null) {\n const outerRef = ((this._outerRef: any): HTMLElement);\n if (typeof initialScrollLeft === 'number') {\n outerRef.scrollLeft = initialScrollLeft;\n }\n if (typeof initialScrollTop === 'number') {\n outerRef.scrollTop = initialScrollTop;\n }\n }\n\n this._callPropsCallbacks();\n }\n\n componentDidUpdate() {\n const { direction } = this.props;\n const { scrollLeft, scrollTop, scrollUpdateWasRequested } = this.state;\n\n if (scrollUpdateWasRequested && this._outerRef != null) {\n // TRICKY According to the spec, scrollLeft should be negative for RTL aligned elements.\n // This is not the case for all browsers though (e.g. Chrome reports values as positive, measured relative to the left).\n // So we need to determine which browser behavior we're dealing with, and mimic it.\n const outerRef = ((this._outerRef: any): HTMLElement);\n if (direction === 'rtl') {\n switch (getRTLOffsetType()) {\n case 'negative':\n outerRef.scrollLeft = -scrollLeft;\n break;\n case 'positive-ascending':\n outerRef.scrollLeft = scrollLeft;\n break;\n default:\n const { clientWidth, scrollWidth } = outerRef;\n outerRef.scrollLeft = scrollWidth - clientWidth - scrollLeft;\n break;\n }\n } else {\n outerRef.scrollLeft = Math.max(0, scrollLeft);\n }\n\n outerRef.scrollTop = Math.max(0, scrollTop);\n }\n\n this._callPropsCallbacks();\n }\n\n componentWillUnmount() {\n if (this._resetIsScrollingTimeoutId !== null) {\n cancelTimeout(this._resetIsScrollingTimeoutId);\n }\n }\n\n render() {\n const {\n children,\n className,\n columnCount,\n direction,\n height,\n innerRef,\n innerElementType,\n innerTagName,\n itemData,\n itemKey = defaultItemKey,\n outerElementType,\n outerTagName,\n rowCount,\n style,\n useIsScrolling,\n width,\n } = this.props;\n const { isScrolling } = this.state;\n\n const [\n columnStartIndex,\n columnStopIndex,\n ] = this._getHorizontalRangeToRender();\n const [rowStartIndex, rowStopIndex] = this._getVerticalRangeToRender();\n\n const items = [];\n if (columnCount > 0 && rowCount) {\n for (\n let rowIndex = rowStartIndex;\n rowIndex <= rowStopIndex;\n rowIndex++\n ) {\n for (\n let columnIndex = columnStartIndex;\n columnIndex <= columnStopIndex;\n columnIndex++\n ) {\n items.push(\n createElement(children, {\n columnIndex,\n data: itemData,\n isScrolling: useIsScrolling ? isScrolling : undefined,\n key: itemKey({ columnIndex, data: itemData, rowIndex }),\n rowIndex,\n style: this._getItemStyle(rowIndex, columnIndex),\n })\n );\n }\n }\n }\n\n // Read this value AFTER items have been created,\n // So their actual sizes (if variable) are taken into consideration.\n const estimatedTotalHeight = getEstimatedTotalHeight(\n this.props,\n this._instanceProps\n );\n const estimatedTotalWidth = getEstimatedTotalWidth(\n this.props,\n this._instanceProps\n );\n\n return createElement(\n outerElementType || outerTagName || 'div',\n {\n className,\n onScroll: this._onScroll,\n ref: this._outerRefSetter,\n style: {\n position: 'relative',\n height,\n width,\n overflow: 'auto',\n WebkitOverflowScrolling: 'touch',\n willChange: 'transform',\n direction,\n ...style,\n },\n },\n createElement(innerElementType || innerTagName || 'div', {\n children: items,\n ref: innerRef,\n style: {\n height: estimatedTotalHeight,\n pointerEvents: isScrolling ? 'none' : undefined,\n width: estimatedTotalWidth,\n },\n })\n );\n }\n\n _callOnItemsRendered: (\n overscanColumnStartIndex: number,\n overscanColumnStopIndex: number,\n overscanRowStartIndex: number,\n overscanRowStopIndex: number,\n visibleColumnStartIndex: number,\n visibleColumnStopIndex: number,\n visibleRowStartIndex: number,\n visibleRowStopIndex: number\n ) => void;\n _callOnItemsRendered = memoizeOne(\n (\n overscanColumnStartIndex: number,\n overscanColumnStopIndex: number,\n overscanRowStartIndex: number,\n overscanRowStopIndex: number,\n visibleColumnStartIndex: number,\n visibleColumnStopIndex: number,\n visibleRowStartIndex: number,\n visibleRowStopIndex: number\n ) =>\n ((this.props.onItemsRendered: any): OnItemsRenderedCallback)({\n overscanColumnStartIndex,\n overscanColumnStopIndex,\n overscanRowStartIndex,\n overscanRowStopIndex,\n visibleColumnStartIndex,\n visibleColumnStopIndex,\n visibleRowStartIndex,\n visibleRowStopIndex,\n })\n );\n\n _callOnScroll: (\n scrollLeft: number,\n scrollTop: number,\n horizontalScrollDirection: ScrollDirection,\n verticalScrollDirection: ScrollDirection,\n scrollUpdateWasRequested: boolean\n ) => void;\n _callOnScroll = memoizeOne(\n (\n scrollLeft: number,\n scrollTop: number,\n horizontalScrollDirection: ScrollDirection,\n verticalScrollDirection: ScrollDirection,\n scrollUpdateWasRequested: boolean\n ) =>\n ((this.props.onScroll: any): OnScrollCallback)({\n horizontalScrollDirection,\n scrollLeft,\n scrollTop,\n verticalScrollDirection,\n scrollUpdateWasRequested,\n })\n );\n\n _callPropsCallbacks() {\n const { columnCount, onItemsRendered, onScroll, rowCount } = this.props;\n\n if (typeof onItemsRendered === 'function') {\n if (columnCount > 0 && rowCount > 0) {\n const [\n overscanColumnStartIndex,\n overscanColumnStopIndex,\n visibleColumnStartIndex,\n visibleColumnStopIndex,\n ] = this._getHorizontalRangeToRender();\n const [\n overscanRowStartIndex,\n overscanRowStopIndex,\n visibleRowStartIndex,\n visibleRowStopIndex,\n ] = this._getVerticalRangeToRender();\n this._callOnItemsRendered(\n overscanColumnStartIndex,\n overscanColumnStopIndex,\n overscanRowStartIndex,\n overscanRowStopIndex,\n visibleColumnStartIndex,\n visibleColumnStopIndex,\n visibleRowStartIndex,\n visibleRowStopIndex\n );\n }\n }\n\n if (typeof onScroll === 'function') {\n const {\n horizontalScrollDirection,\n scrollLeft,\n scrollTop,\n scrollUpdateWasRequested,\n verticalScrollDirection,\n } = this.state;\n this._callOnScroll(\n scrollLeft,\n scrollTop,\n horizontalScrollDirection,\n verticalScrollDirection,\n scrollUpdateWasRequested\n );\n }\n }\n\n // Lazily create and cache item styles while scrolling,\n // So that pure component sCU will prevent re-renders.\n // We maintain this cache, and pass a style prop rather than index,\n // So that List can clear cached styles and force item re-render if necessary.\n _getItemStyle: (rowIndex: number, columnIndex: number) => Object;\n _getItemStyle = (rowIndex: number, columnIndex: number): Object => {\n const { columnWidth, direction, rowHeight } = this.props;\n\n const itemStyleCache = this._getItemStyleCache(\n shouldResetStyleCacheOnItemSizeChange && columnWidth,\n shouldResetStyleCacheOnItemSizeChange && direction,\n shouldResetStyleCacheOnItemSizeChange && rowHeight\n );\n\n const key = `${rowIndex}:${columnIndex}`;\n\n let style;\n if (itemStyleCache.hasOwnProperty(key)) {\n style = itemStyleCache[key];\n } else {\n const offset = getColumnOffset(\n this.props,\n columnIndex,\n this._instanceProps\n );\n const isRtl = direction === 'rtl';\n itemStyleCache[key] = style = {\n position: 'absolute',\n left: isRtl ? undefined : offset,\n right: isRtl ? offset : undefined,\n top: getRowOffset(this.props, rowIndex, this._instanceProps),\n height: getRowHeight(this.props, rowIndex, this._instanceProps),\n width: getColumnWidth(this.props, columnIndex, this._instanceProps),\n };\n }\n\n return style;\n };\n\n _getItemStyleCache: (_: any, __: any, ___: any) => ItemStyleCache;\n _getItemStyleCache = memoizeOne((_: any, __: any, ___: any) => ({}));\n\n _getHorizontalRangeToRender(): [number, number, number, number] {\n const {\n columnCount,\n overscanColumnCount,\n overscanColumnsCount,\n overscanCount,\n rowCount,\n } = this.props;\n const { horizontalScrollDirection, isScrolling, scrollLeft } = this.state;\n\n const overscanCountResolved: number =\n overscanColumnCount || overscanColumnsCount || overscanCount || 1;\n\n if (columnCount === 0 || rowCount === 0) {\n return [0, 0, 0, 0];\n }\n\n const startIndex = getColumnStartIndexForOffset(\n this.props,\n scrollLeft,\n this._instanceProps\n );\n const stopIndex = getColumnStopIndexForStartIndex(\n this.props,\n startIndex,\n scrollLeft,\n this._instanceProps\n );\n\n // Overscan by one item in each direction so that tab/focus works.\n // If there isn't at least one extra item, tab loops back around.\n const overscanBackward =\n !isScrolling || horizontalScrollDirection === 'backward'\n ? Math.max(1, overscanCountResolved)\n : 1;\n const overscanForward =\n !isScrolling || horizontalScrollDirection === 'forward'\n ? Math.max(1, overscanCountResolved)\n : 1;\n\n return [\n Math.max(0, startIndex - overscanBackward),\n Math.max(0, Math.min(columnCount - 1, stopIndex + overscanForward)),\n startIndex,\n stopIndex,\n ];\n }\n\n _getVerticalRangeToRender(): [number, number, number, number] {\n const {\n columnCount,\n overscanCount,\n overscanRowCount,\n overscanRowsCount,\n rowCount,\n } = this.props;\n const { isScrolling, verticalScrollDirection, scrollTop } = this.state;\n\n const overscanCountResolved: number =\n overscanRowCount || overscanRowsCount || overscanCount || 1;\n\n if (columnCount === 0 || rowCount === 0) {\n return [0, 0, 0, 0];\n }\n\n const startIndex = getRowStartIndexForOffset(\n this.props,\n scrollTop,\n this._instanceProps\n );\n const stopIndex = getRowStopIndexForStartIndex(\n this.props,\n startIndex,\n scrollTop,\n this._instanceProps\n );\n\n // Overscan by one item in each direction so that tab/focus works.\n // If there isn't at least one extra item, tab loops back around.\n const overscanBackward =\n !isScrolling || verticalScrollDirection === 'backward'\n ? Math.max(1, overscanCountResolved)\n : 1;\n const overscanForward =\n !isScrolling || verticalScrollDirection === 'forward'\n ? Math.max(1, overscanCountResolved)\n : 1;\n\n return [\n Math.max(0, startIndex - overscanBackward),\n Math.max(0, Math.min(rowCount - 1, stopIndex + overscanForward)),\n startIndex,\n stopIndex,\n ];\n }\n\n _onScroll = (event: ScrollEvent): void => {\n const {\n clientHeight,\n clientWidth,\n scrollLeft,\n scrollTop,\n scrollHeight,\n scrollWidth,\n } = event.currentTarget;\n this.setState(prevState => {\n if (\n prevState.scrollLeft === scrollLeft &&\n prevState.scrollTop === scrollTop\n ) {\n // Scroll position may have been updated by cDM/cDU,\n // In which case we don't need to trigger another render,\n // And we don't want to update state.isScrolling.\n return null;\n }\n\n const { direction } = this.props;\n\n // TRICKY According to the spec, scrollLeft should be negative for RTL aligned elements.\n // This is not the case for all browsers though (e.g. Chrome reports values as positive, measured relative to the left).\n // It's also easier for this component if we convert offsets to the same format as they would be in for ltr.\n // So the simplest solution is to determine which browser behavior we're dealing with, and convert based on it.\n let calculatedScrollLeft = scrollLeft;\n if (direction === 'rtl') {\n switch (getRTLOffsetType()) {\n case 'negative':\n calculatedScrollLeft = -scrollLeft;\n break;\n case 'positive-descending':\n calculatedScrollLeft = scrollWidth - clientWidth - scrollLeft;\n break;\n }\n }\n\n // Prevent Safari's elastic scrolling from causing visual shaking when scrolling past bounds.\n calculatedScrollLeft = Math.max(\n 0,\n Math.min(calculatedScrollLeft, scrollWidth - clientWidth)\n );\n const calculatedScrollTop = Math.max(\n 0,\n Math.min(scrollTop, scrollHeight - clientHeight)\n );\n\n return {\n isScrolling: true,\n horizontalScrollDirection:\n prevState.scrollLeft < scrollLeft ? 'forward' : 'backward',\n scrollLeft: calculatedScrollLeft,\n scrollTop: calculatedScrollTop,\n verticalScrollDirection:\n prevState.scrollTop < scrollTop ? 'forward' : 'backward',\n scrollUpdateWasRequested: false,\n };\n }, this._resetIsScrollingDebounced);\n };\n\n _outerRefSetter = (ref: any): void => {\n const { outerRef } = this.props;\n\n this._outerRef = ((ref: any): HTMLDivElement);\n\n if (typeof outerRef === 'function') {\n outerRef(ref);\n } else if (\n outerRef != null &&\n typeof outerRef === 'object' &&\n outerRef.hasOwnProperty('current')\n ) {\n outerRef.current = ref;\n }\n };\n\n _resetIsScrollingDebounced = () => {\n if (this._resetIsScrollingTimeoutId !== null) {\n cancelTimeout(this._resetIsScrollingTimeoutId);\n }\n\n this._resetIsScrollingTimeoutId = requestTimeout(\n this._resetIsScrolling,\n IS_SCROLLING_DEBOUNCE_INTERVAL\n );\n };\n\n _resetIsScrolling = () => {\n this._resetIsScrollingTimeoutId = null;\n\n this.setState({ isScrolling: false }, () => {\n // Clear style cache after state update has been committed.\n // This way we don't break pure sCU for items that don't use isScrolling param.\n this._getItemStyleCache(-1);\n });\n };\n };\n}\n\nconst validateSharedProps = (\n {\n children,\n direction,\n height,\n innerTagName,\n outerTagName,\n overscanColumnsCount,\n overscanCount,\n overscanRowsCount,\n width,\n }: Props,\n { instance }: State\n): void => {\n if (process.env.NODE_ENV !== 'production') {\n if (typeof overscanCount === 'number') {\n if (devWarningsOverscanCount && !devWarningsOverscanCount.has(instance)) {\n devWarningsOverscanCount.add(instance);\n console.warn(\n 'The overscanCount prop has been deprecated. ' +\n 'Please use the overscanColumnCount and overscanRowCount props instead.'\n );\n }\n }\n\n if (\n typeof overscanColumnsCount === 'number' ||\n typeof overscanRowsCount === 'number'\n ) {\n if (\n devWarningsOverscanRowsColumnsCount &&\n !devWarningsOverscanRowsColumnsCount.has(instance)\n ) {\n devWarningsOverscanRowsColumnsCount.add(instance);\n console.warn(\n 'The overscanColumnsCount and overscanRowsCount props have been deprecated. ' +\n 'Please use the overscanColumnCount and overscanRowCount props instead.'\n );\n }\n }\n\n if (innerTagName != null || outerTagName != null) {\n if (devWarningsTagName && !devWarningsTagName.has(instance)) {\n devWarningsTagName.add(instance);\n console.warn(\n 'The innerTagName and outerTagName props have been deprecated. ' +\n 'Please use the innerElementType and outerElementType props instead.'\n );\n }\n }\n\n if (children == null) {\n throw Error(\n 'An invalid \"children\" prop has been specified. ' +\n 'Value should be a React component. ' +\n `\"${children === null ? 'null' : typeof children}\" was specified.`\n );\n }\n\n switch (direction) {\n case 'ltr':\n case 'rtl':\n // Valid values\n break;\n default:\n throw Error(\n 'An invalid \"direction\" prop has been specified. ' +\n 'Value should be either \"ltr\" or \"rtl\". ' +\n `\"${direction}\" was specified.`\n );\n }\n\n if (typeof width !== 'number') {\n throw Error(\n 'An invalid \"width\" prop has been specified. ' +\n 'Grids must specify a number for width. ' +\n `\"${width === null ? 'null' : typeof width}\" was specified.`\n );\n }\n\n if (typeof height !== 'number') {\n throw Error(\n 'An invalid \"height\" prop has been specified. ' +\n 'Grids must specify a number for height. ' +\n `\"${height === null ? 'null' : typeof height}\" was specified.`\n );\n }\n }\n};\n", "// @flow\n\nimport createGridComponent from './createGridComponent';\n\nimport type { Props, ScrollToAlign } from './createGridComponent';\n\nconst DEFAULT_ESTIMATED_ITEM_SIZE = 50;\n\ntype VariableSizeProps = {|\n estimatedColumnWidth: number,\n estimatedRowHeight: number,\n ...Props,\n|};\n\ntype itemSizeGetter = (index: number) => number;\ntype ItemType = 'column' | 'row';\n\ntype ItemMetadata = {|\n offset: number,\n size: number,\n|};\ntype ItemMetadataMap = { [index: number]: ItemMetadata };\ntype InstanceProps = {|\n columnMetadataMap: ItemMetadataMap,\n estimatedColumnWidth: number,\n estimatedRowHeight: number,\n lastMeasuredColumnIndex: number,\n lastMeasuredRowIndex: number,\n rowMetadataMap: ItemMetadataMap,\n|};\n\nconst getEstimatedTotalHeight = (\n { rowCount }: Props,\n { rowMetadataMap, estimatedRowHeight, lastMeasuredRowIndex }: InstanceProps\n) => {\n let totalSizeOfMeasuredRows = 0;\n\n // Edge case check for when the number of items decreases while a scroll is in progress.\n // https://github.com/bvaughn/react-window/pull/138\n if (lastMeasuredRowIndex >= rowCount) {\n lastMeasuredRowIndex = rowCount - 1;\n }\n\n if (lastMeasuredRowIndex >= 0) {\n const itemMetadata = rowMetadataMap[lastMeasuredRowIndex];\n totalSizeOfMeasuredRows = itemMetadata.offset + itemMetadata.size;\n }\n\n const numUnmeasuredItems = rowCount - lastMeasuredRowIndex - 1;\n const totalSizeOfUnmeasuredItems = numUnmeasuredItems * estimatedRowHeight;\n\n return totalSizeOfMeasuredRows + totalSizeOfUnmeasuredItems;\n};\n\nconst getEstimatedTotalWidth = (\n { columnCount }: Props,\n {\n columnMetadataMap,\n estimatedColumnWidth,\n lastMeasuredColumnIndex,\n }: InstanceProps\n) => {\n let totalSizeOfMeasuredRows = 0;\n\n // Edge case check for when the number of items decreases while a scroll is in progress.\n // https://github.com/bvaughn/react-window/pull/138\n if (lastMeasuredColumnIndex >= columnCount) {\n lastMeasuredColumnIndex = columnCount - 1;\n }\n\n if (lastMeasuredColumnIndex >= 0) {\n const itemMetadata = columnMetadataMap[lastMeasuredColumnIndex];\n totalSizeOfMeasuredRows = itemMetadata.offset + itemMetadata.size;\n }\n\n const numUnmeasuredItems = columnCount - lastMeasuredColumnIndex - 1;\n const totalSizeOfUnmeasuredItems = numUnmeasuredItems * estimatedColumnWidth;\n\n return totalSizeOfMeasuredRows + totalSizeOfUnmeasuredItems;\n};\n\nconst getItemMetadata = (\n itemType: ItemType,\n props: Props,\n index: number,\n instanceProps: InstanceProps\n): ItemMetadata => {\n let itemMetadataMap, itemSize, lastMeasuredIndex;\n if (itemType === 'column') {\n itemMetadataMap = instanceProps.columnMetadataMap;\n itemSize = ((props.columnWidth: any): itemSizeGetter);\n lastMeasuredIndex = instanceProps.lastMeasuredColumnIndex;\n } else {\n itemMetadataMap = instanceProps.rowMetadataMap;\n itemSize = ((props.rowHeight: any): itemSizeGetter);\n lastMeasuredIndex = instanceProps.lastMeasuredRowIndex;\n }\n\n if (index > lastMeasuredIndex) {\n let offset = 0;\n if (lastMeasuredIndex >= 0) {\n const itemMetadata = itemMetadataMap[lastMeasuredIndex];\n offset = itemMetadata.offset + itemMetadata.size;\n }\n\n for (let i = lastMeasuredIndex + 1; i <= index; i++) {\n let size = itemSize(i);\n\n itemMetadataMap[i] = {\n offset,\n size,\n };\n\n offset += size;\n }\n\n if (itemType === 'column') {\n instanceProps.lastMeasuredColumnIndex = index;\n } else {\n instanceProps.lastMeasuredRowIndex = index;\n }\n }\n\n return itemMetadataMap[index];\n};\n\nconst findNearestItem = (\n itemType: ItemType,\n props: Props,\n instanceProps: InstanceProps,\n offset: number\n) => {\n let itemMetadataMap, lastMeasuredIndex;\n if (itemType === 'column') {\n itemMetadataMap = instanceProps.columnMetadataMap;\n lastMeasuredIndex = instanceProps.lastMeasuredColumnIndex;\n } else {\n itemMetadataMap = instanceProps.rowMetadataMap;\n lastMeasuredIndex = instanceProps.lastMeasuredRowIndex;\n }\n\n const lastMeasuredItemOffset =\n lastMeasuredIndex > 0 ? itemMetadataMap[lastMeasuredIndex].offset : 0;\n\n if (lastMeasuredItemOffset >= offset) {\n // If we've already measured items within this range just use a binary search as it's faster.\n return findNearestItemBinarySearch(\n itemType,\n props,\n instanceProps,\n lastMeasuredIndex,\n 0,\n offset\n );\n } else {\n // If we haven't yet measured this high, fallback to an exponential search with an inner binary search.\n // The exponential search avoids pre-computing sizes for the full set of items as a binary search would.\n // The overall complexity for this approach is O(log n).\n return findNearestItemExponentialSearch(\n itemType,\n props,\n instanceProps,\n Math.max(0, lastMeasuredIndex),\n offset\n );\n }\n};\n\nconst findNearestItemBinarySearch = (\n itemType: ItemType,\n props: Props,\n instanceProps: InstanceProps,\n high: number,\n low: number,\n offset: number\n): number => {\n while (low <= high) {\n const middle = low + Math.floor((high - low) / 2);\n const currentOffset = getItemMetadata(\n itemType,\n props,\n middle,\n instanceProps\n ).offset;\n\n if (currentOffset === offset) {\n return middle;\n } else if (currentOffset < offset) {\n low = middle + 1;\n } else if (currentOffset > offset) {\n high = middle - 1;\n }\n }\n\n if (low > 0) {\n return low - 1;\n } else {\n return 0;\n }\n};\n\nconst findNearestItemExponentialSearch = (\n itemType: ItemType,\n props: Props,\n instanceProps: InstanceProps,\n index: number,\n offset: number\n): number => {\n const itemCount = itemType === 'column' ? props.columnCount : props.rowCount;\n let interval = 1;\n\n while (\n index < itemCount &&\n getItemMetadata(itemType, props, index, instanceProps).offset < offset\n ) {\n index += interval;\n interval *= 2;\n }\n\n return findNearestItemBinarySearch(\n itemType,\n props,\n instanceProps,\n Math.min(index, itemCount - 1),\n Math.floor(index / 2),\n offset\n );\n};\n\nconst getOffsetForIndexAndAlignment = (\n itemType: ItemType,\n props: Props,\n index: number,\n align: ScrollToAlign,\n scrollOffset: number,\n instanceProps: InstanceProps,\n scrollbarSize: number\n): number => {\n const size = itemType === 'column' ? props.width : props.height;\n const itemMetadata = getItemMetadata(itemType, props, index, instanceProps);\n\n // Get estimated total size after ItemMetadata is computed,\n // To ensure it reflects actual measurements instead of just estimates.\n const estimatedTotalSize =\n itemType === 'column'\n ? getEstimatedTotalWidth(props, instanceProps)\n : getEstimatedTotalHeight(props, instanceProps);\n\n const maxOffset = Math.max(\n 0,\n Math.min(estimatedTotalSize - size, itemMetadata.offset)\n );\n const minOffset = Math.max(\n 0,\n itemMetadata.offset - size + scrollbarSize + itemMetadata.size\n );\n\n if (align === 'smart') {\n if (scrollOffset >= minOffset - size && scrollOffset <= maxOffset + size) {\n align = 'auto';\n } else {\n align = 'center';\n }\n }\n\n switch (align) {\n case 'start':\n return maxOffset;\n case 'end':\n return minOffset;\n case 'center':\n return Math.round(minOffset + (maxOffset - minOffset) / 2);\n case 'auto':\n default:\n if (scrollOffset >= minOffset && scrollOffset <= maxOffset) {\n return scrollOffset;\n } else if (minOffset > maxOffset) {\n // Because we only take into account the scrollbar size when calculating minOffset\n // this value can be larger than maxOffset when at the end of the list\n return minOffset;\n } else if (scrollOffset < minOffset) {\n return minOffset;\n } else {\n return maxOffset;\n }\n }\n};\n\nconst VariableSizeGrid = createGridComponent({\n getColumnOffset: (\n props: Props,\n index: number,\n instanceProps: InstanceProps\n ): number => getItemMetadata('column', props, index, instanceProps).offset,\n\n getColumnStartIndexForOffset: (\n props: Props,\n scrollLeft: number,\n instanceProps: InstanceProps\n ): number => findNearestItem('column', props, instanceProps, scrollLeft),\n\n getColumnStopIndexForStartIndex: (\n props: Props,\n startIndex: number,\n scrollLeft: number,\n instanceProps: InstanceProps\n ): number => {\n const { columnCount, width } = props;\n\n const itemMetadata = getItemMetadata(\n 'column',\n props,\n startIndex,\n instanceProps\n );\n const maxOffset = scrollLeft + width;\n\n let offset = itemMetadata.offset + itemMetadata.size;\n let stopIndex = startIndex;\n\n while (stopIndex < columnCount - 1 && offset < maxOffset) {\n stopIndex++;\n offset += getItemMetadata('column', props, stopIndex, instanceProps).size;\n }\n\n return stopIndex;\n },\n\n getColumnWidth: (\n props: Props,\n index: number,\n instanceProps: InstanceProps\n ): number => instanceProps.columnMetadataMap[index].size,\n\n getEstimatedTotalHeight,\n getEstimatedTotalWidth,\n\n getOffsetForColumnAndAlignment: (\n props: Props,\n index: number,\n align: ScrollToAlign,\n scrollOffset: number,\n instanceProps: InstanceProps,\n scrollbarSize: number\n ): number =>\n getOffsetForIndexAndAlignment(\n 'column',\n props,\n index,\n align,\n scrollOffset,\n instanceProps,\n scrollbarSize\n ),\n\n getOffsetForRowAndAlignment: (\n props: Props,\n index: number,\n align: ScrollToAlign,\n scrollOffset: number,\n instanceProps: InstanceProps,\n scrollbarSize: number\n ): number =>\n getOffsetForIndexAndAlignment(\n 'row',\n props,\n index,\n align,\n scrollOffset,\n instanceProps,\n scrollbarSize\n ),\n\n getRowOffset: (\n props: Props,\n index: number,\n instanceProps: InstanceProps\n ): number => getItemMetadata('row', props, index, instanceProps).offset,\n\n getRowHeight: (\n props: Props,\n index: number,\n instanceProps: InstanceProps\n ): number => instanceProps.rowMetadataMap[index].size,\n\n getRowStartIndexForOffset: (\n props: Props,\n scrollTop: number,\n instanceProps: InstanceProps\n ): number => findNearestItem('row', props, instanceProps, scrollTop),\n\n getRowStopIndexForStartIndex: (\n props: Props,\n startIndex: number,\n scrollTop: number,\n instanceProps: InstanceProps\n ): number => {\n const { rowCount, height } = props;\n\n const itemMetadata = getItemMetadata(\n 'row',\n props,\n startIndex,\n instanceProps\n );\n const maxOffset = scrollTop + height;\n\n let offset = itemMetadata.offset + itemMetadata.size;\n let stopIndex = startIndex;\n\n while (stopIndex < rowCount - 1 && offset < maxOffset) {\n stopIndex++;\n offset += getItemMetadata('row', props, stopIndex, instanceProps).size;\n }\n\n return stopIndex;\n },\n\n initInstanceProps(props: Props, instance: any): InstanceProps {\n const {\n estimatedColumnWidth,\n estimatedRowHeight,\n } = ((props: any): VariableSizeProps);\n\n const instanceProps = {\n columnMetadataMap: {},\n estimatedColumnWidth: estimatedColumnWidth || DEFAULT_ESTIMATED_ITEM_SIZE,\n estimatedRowHeight: estimatedRowHeight || DEFAULT_ESTIMATED_ITEM_SIZE,\n lastMeasuredColumnIndex: -1,\n lastMeasuredRowIndex: -1,\n rowMetadataMap: {},\n };\n\n instance.resetAfterColumnIndex = (\n columnIndex: number,\n shouldForceUpdate?: boolean = true\n ) => {\n instance.resetAfterIndices({ columnIndex, shouldForceUpdate });\n };\n\n instance.resetAfterRowIndex = (\n rowIndex: number,\n shouldForceUpdate?: boolean = true\n ) => {\n instance.resetAfterIndices({ rowIndex, shouldForceUpdate });\n };\n\n instance.resetAfterIndices = ({\n columnIndex,\n rowIndex,\n shouldForceUpdate = true,\n }: {\n columnIndex?: number,\n rowIndex?: number,\n shouldForceUpdate: boolean,\n }) => {\n if (typeof columnIndex === 'number') {\n instanceProps.lastMeasuredColumnIndex = Math.min(\n instanceProps.lastMeasuredColumnIndex,\n columnIndex - 1\n );\n }\n if (typeof rowIndex === 'number') {\n instanceProps.lastMeasuredRowIndex = Math.min(\n instanceProps.lastMeasuredRowIndex,\n rowIndex - 1\n );\n }\n\n // We could potentially optimize further by only evicting styles after this index,\n // But since styles are only cached while scrolling is in progress-\n // It seems an unnecessary optimization.\n // It's unlikely that resetAfterIndex() will be called while a user is scrolling.\n instance._getItemStyleCache(-1);\n\n if (shouldForceUpdate) {\n instance.forceUpdate();\n }\n };\n\n return instanceProps;\n },\n\n shouldResetStyleCacheOnItemSizeChange: false,\n\n validateProps: ({ columnWidth, rowHeight }: Props): void => {\n if (process.env.NODE_ENV !== 'production') {\n if (typeof columnWidth !== 'function') {\n throw Error(\n 'An invalid \"columnWidth\" prop has been specified. ' +\n 'Value should be a function. ' +\n `\"${\n columnWidth === null ? 'null' : typeof columnWidth\n }\" was specified.`\n );\n } else if (typeof rowHeight !== 'function') {\n throw Error(\n 'An invalid \"rowHeight\" prop has been specified. ' +\n 'Value should be a function. ' +\n `\"${rowHeight === null ? 'null' : typeof rowHeight}\" was specified.`\n );\n }\n }\n },\n});\n\nexport default VariableSizeGrid;\n", "// @flow\n\nimport memoizeOne from 'memoize-one';\nimport { createElement, PureComponent } from 'react';\nimport { cancelTimeout, requestTimeout } from './timer';\nimport { getScrollbarSize, getRTLOffsetType } from './domHelpers';\n\nimport type { TimeoutID } from './timer';\n\nexport type ScrollToAlign = 'auto' | 'smart' | 'center' | 'start' | 'end';\n\ntype itemSize = number | ((index: number) => number);\n// TODO Deprecate directions \"horizontal\" and \"vertical\"\ntype Direction = 'ltr' | 'rtl' | 'horizontal' | 'vertical';\ntype Layout = 'horizontal' | 'vertical';\n\ntype RenderComponentProps = {|\n data: T,\n index: number,\n isScrolling?: boolean,\n style: Object,\n|};\ntype RenderComponent = React$ComponentType<$Shape>>;\n\ntype ScrollDirection = 'forward' | 'backward';\n\ntype onItemsRenderedCallback = ({\n overscanStartIndex: number,\n overscanStopIndex: number,\n visibleStartIndex: number,\n visibleStopIndex: number,\n}) => void;\ntype onScrollCallback = ({\n scrollDirection: ScrollDirection,\n scrollOffset: number,\n scrollUpdateWasRequested: boolean,\n}) => void;\n\ntype ScrollEvent = SyntheticEvent;\ntype ItemStyleCache = { [index: number]: Object };\n\ntype OuterProps = {|\n children: React$Node,\n className: string | void,\n onScroll: ScrollEvent => void,\n style: {\n [string]: mixed,\n },\n|};\n\ntype InnerProps = {|\n children: React$Node,\n style: {\n [string]: mixed,\n },\n|};\n\nexport type Props = {|\n children: RenderComponent,\n className?: string,\n direction: Direction,\n height: number | string,\n initialScrollOffset?: number,\n innerRef?: any,\n innerElementType?: string | React$AbstractComponent,\n innerTagName?: string, // deprecated\n itemCount: number,\n itemData: T,\n itemKey?: (index: number, data: T) => any,\n itemSize: itemSize,\n layout: Layout,\n onItemsRendered?: onItemsRenderedCallback,\n onScroll?: onScrollCallback,\n outerRef?: any,\n outerElementType?: string | React$AbstractComponent,\n outerTagName?: string, // deprecated\n overscanCount: number,\n style?: Object,\n useIsScrolling: boolean,\n width: number | string,\n|};\n\ntype State = {|\n instance: any,\n isScrolling: boolean,\n scrollDirection: ScrollDirection,\n scrollOffset: number,\n scrollUpdateWasRequested: boolean,\n|};\n\ntype GetItemOffset = (\n props: Props,\n index: number,\n instanceProps: any\n) => number;\ntype GetItemSize = (\n props: Props,\n index: number,\n instanceProps: any\n) => number;\ntype GetEstimatedTotalSize = (props: Props, instanceProps: any) => number;\ntype GetOffsetForIndexAndAlignment = (\n props: Props,\n index: number,\n align: ScrollToAlign,\n scrollOffset: number,\n instanceProps: any\n) => number;\ntype GetStartIndexForOffset = (\n props: Props,\n offset: number,\n instanceProps: any\n) => number;\ntype GetStopIndexForStartIndex = (\n props: Props,\n startIndex: number,\n scrollOffset: number,\n instanceProps: any\n) => number;\ntype InitInstanceProps = (props: Props, instance: any) => any;\ntype ValidateProps = (props: Props) => void;\n\nconst IS_SCROLLING_DEBOUNCE_INTERVAL = 150;\n\nconst defaultItemKey = (index: number, data: any) => index;\n\n// In DEV mode, this Set helps us only log a warning once per component instance.\n// This avoids spamming the console every time a render happens.\nlet devWarningsDirection = null;\nlet devWarningsTagName = null;\nif (process.env.NODE_ENV !== 'production') {\n if (typeof window !== 'undefined' && typeof window.WeakSet !== 'undefined') {\n devWarningsDirection = new WeakSet();\n devWarningsTagName = new WeakSet();\n }\n}\n\nexport default function createListComponent({\n getItemOffset,\n getEstimatedTotalSize,\n getItemSize,\n getOffsetForIndexAndAlignment,\n getStartIndexForOffset,\n getStopIndexForStartIndex,\n initInstanceProps,\n shouldResetStyleCacheOnItemSizeChange,\n validateProps,\n}: {|\n getItemOffset: GetItemOffset,\n getEstimatedTotalSize: GetEstimatedTotalSize,\n getItemSize: GetItemSize,\n getOffsetForIndexAndAlignment: GetOffsetForIndexAndAlignment,\n getStartIndexForOffset: GetStartIndexForOffset,\n getStopIndexForStartIndex: GetStopIndexForStartIndex,\n initInstanceProps: InitInstanceProps,\n shouldResetStyleCacheOnItemSizeChange: boolean,\n validateProps: ValidateProps,\n|}) {\n return class List extends PureComponent, State> {\n _instanceProps: any = initInstanceProps(this.props, this);\n _outerRef: ?HTMLDivElement;\n _resetIsScrollingTimeoutId: TimeoutID | null = null;\n\n static defaultProps = {\n direction: 'ltr',\n itemData: undefined,\n layout: 'vertical',\n overscanCount: 2,\n useIsScrolling: false,\n };\n\n state: State = {\n instance: this,\n isScrolling: false,\n scrollDirection: 'forward',\n scrollOffset:\n typeof this.props.initialScrollOffset === 'number'\n ? this.props.initialScrollOffset\n : 0,\n scrollUpdateWasRequested: false,\n };\n\n // Always use explicit constructor for React components.\n // It produces less code after transpilation. (#26)\n // eslint-disable-next-line no-useless-constructor\n constructor(props: Props) {\n super(props);\n }\n\n static getDerivedStateFromProps(\n nextProps: Props,\n prevState: State\n ): $Shape | null {\n validateSharedProps(nextProps, prevState);\n validateProps(nextProps);\n return null;\n }\n\n scrollTo(scrollOffset: number): void {\n scrollOffset = Math.max(0, scrollOffset);\n\n this.setState(prevState => {\n if (prevState.scrollOffset === scrollOffset) {\n return null;\n }\n return {\n scrollDirection:\n prevState.scrollOffset < scrollOffset ? 'forward' : 'backward',\n scrollOffset: scrollOffset,\n scrollUpdateWasRequested: true,\n };\n }, this._resetIsScrollingDebounced);\n }\n\n scrollToItem(index: number, align: ScrollToAlign = 'auto'): void {\n const { itemCount, layout } = this.props;\n const { scrollOffset } = this.state;\n\n index = Math.max(0, Math.min(index, itemCount - 1));\n\n // The scrollbar size should be considered when scrolling an item into view, to ensure it's fully visible.\n // But we only need to account for its size when it's actually visible.\n // This is an edge case for lists; normally they only scroll in the dominant direction.\n let scrollbarSize = 0;\n if (this._outerRef) {\n const outerRef = ((this._outerRef: any): HTMLElement);\n if (layout === 'vertical') {\n scrollbarSize =\n outerRef.scrollWidth > outerRef.clientWidth\n ? getScrollbarSize()\n : 0;\n } else {\n scrollbarSize =\n outerRef.scrollHeight > outerRef.clientHeight\n ? getScrollbarSize()\n : 0;\n }\n }\n\n this.scrollTo(\n getOffsetForIndexAndAlignment(\n this.props,\n index,\n align,\n scrollOffset,\n this._instanceProps,\n scrollbarSize\n )\n );\n }\n\n componentDidMount() {\n const { direction, initialScrollOffset, layout } = this.props;\n\n if (typeof initialScrollOffset === 'number' && this._outerRef != null) {\n const outerRef = ((this._outerRef: any): HTMLElement);\n // TODO Deprecate direction \"horizontal\"\n if (direction === 'horizontal' || layout === 'horizontal') {\n outerRef.scrollLeft = initialScrollOffset;\n } else {\n outerRef.scrollTop = initialScrollOffset;\n }\n }\n\n this._callPropsCallbacks();\n }\n\n componentDidUpdate() {\n const { direction, layout } = this.props;\n const { scrollOffset, scrollUpdateWasRequested } = this.state;\n\n if (scrollUpdateWasRequested && this._outerRef != null) {\n const outerRef = ((this._outerRef: any): HTMLElement);\n\n // TODO Deprecate direction \"horizontal\"\n if (direction === 'horizontal' || layout === 'horizontal') {\n if (direction === 'rtl') {\n // TRICKY According to the spec, scrollLeft should be negative for RTL aligned elements.\n // This is not the case for all browsers though (e.g. Chrome reports values as positive, measured relative to the left).\n // So we need to determine which browser behavior we're dealing with, and mimic it.\n switch (getRTLOffsetType()) {\n case 'negative':\n outerRef.scrollLeft = -scrollOffset;\n break;\n case 'positive-ascending':\n outerRef.scrollLeft = scrollOffset;\n break;\n default:\n const { clientWidth, scrollWidth } = outerRef;\n outerRef.scrollLeft = scrollWidth - clientWidth - scrollOffset;\n break;\n }\n } else {\n outerRef.scrollLeft = scrollOffset;\n }\n } else {\n outerRef.scrollTop = scrollOffset;\n }\n }\n\n this._callPropsCallbacks();\n }\n\n componentWillUnmount() {\n if (this._resetIsScrollingTimeoutId !== null) {\n cancelTimeout(this._resetIsScrollingTimeoutId);\n }\n }\n\n render() {\n const {\n children,\n className,\n direction,\n height,\n innerRef,\n innerElementType,\n innerTagName,\n itemCount,\n itemData,\n itemKey = defaultItemKey,\n layout,\n outerElementType,\n outerTagName,\n style,\n useIsScrolling,\n width,\n } = this.props;\n const { isScrolling } = this.state;\n\n // TODO Deprecate direction \"horizontal\"\n const isHorizontal =\n direction === 'horizontal' || layout === 'horizontal';\n\n const onScroll = isHorizontal\n ? this._onScrollHorizontal\n : this._onScrollVertical;\n\n const [startIndex, stopIndex] = this._getRangeToRender();\n\n const items = [];\n if (itemCount > 0) {\n for (let index = startIndex; index <= stopIndex; index++) {\n items.push(\n createElement(children, {\n data: itemData,\n key: itemKey(index, itemData),\n index,\n isScrolling: useIsScrolling ? isScrolling : undefined,\n style: this._getItemStyle(index),\n })\n );\n }\n }\n\n // Read this value AFTER items have been created,\n // So their actual sizes (if variable) are taken into consideration.\n const estimatedTotalSize = getEstimatedTotalSize(\n this.props,\n this._instanceProps\n );\n\n return createElement(\n outerElementType || outerTagName || 'div',\n {\n className,\n onScroll,\n ref: this._outerRefSetter,\n style: {\n position: 'relative',\n height,\n width,\n overflow: 'auto',\n WebkitOverflowScrolling: 'touch',\n willChange: 'transform',\n direction,\n ...style,\n },\n },\n createElement(innerElementType || innerTagName || 'div', {\n children: items,\n ref: innerRef,\n style: {\n height: isHorizontal ? '100%' : estimatedTotalSize,\n pointerEvents: isScrolling ? 'none' : undefined,\n width: isHorizontal ? estimatedTotalSize : '100%',\n },\n })\n );\n }\n\n _callOnItemsRendered: (\n overscanStartIndex: number,\n overscanStopIndex: number,\n visibleStartIndex: number,\n visibleStopIndex: number\n ) => void;\n _callOnItemsRendered = memoizeOne(\n (\n overscanStartIndex: number,\n overscanStopIndex: number,\n visibleStartIndex: number,\n visibleStopIndex: number\n ) =>\n ((this.props.onItemsRendered: any): onItemsRenderedCallback)({\n overscanStartIndex,\n overscanStopIndex,\n visibleStartIndex,\n visibleStopIndex,\n })\n );\n\n _callOnScroll: (\n scrollDirection: ScrollDirection,\n scrollOffset: number,\n scrollUpdateWasRequested: boolean\n ) => void;\n _callOnScroll = memoizeOne(\n (\n scrollDirection: ScrollDirection,\n scrollOffset: number,\n scrollUpdateWasRequested: boolean\n ) =>\n ((this.props.onScroll: any): onScrollCallback)({\n scrollDirection,\n scrollOffset,\n scrollUpdateWasRequested,\n })\n );\n\n _callPropsCallbacks() {\n if (typeof this.props.onItemsRendered === 'function') {\n const { itemCount } = this.props;\n if (itemCount > 0) {\n const [\n overscanStartIndex,\n overscanStopIndex,\n visibleStartIndex,\n visibleStopIndex,\n ] = this._getRangeToRender();\n this._callOnItemsRendered(\n overscanStartIndex,\n overscanStopIndex,\n visibleStartIndex,\n visibleStopIndex\n );\n }\n }\n\n if (typeof this.props.onScroll === 'function') {\n const {\n scrollDirection,\n scrollOffset,\n scrollUpdateWasRequested,\n } = this.state;\n this._callOnScroll(\n scrollDirection,\n scrollOffset,\n scrollUpdateWasRequested\n );\n }\n }\n\n // Lazily create and cache item styles while scrolling,\n // So that pure component sCU will prevent re-renders.\n // We maintain this cache, and pass a style prop rather than index,\n // So that List can clear cached styles and force item re-render if necessary.\n _getItemStyle: (index: number) => Object;\n _getItemStyle = (index: number): Object => {\n const { direction, itemSize, layout } = this.props;\n\n const itemStyleCache = this._getItemStyleCache(\n shouldResetStyleCacheOnItemSizeChange && itemSize,\n shouldResetStyleCacheOnItemSizeChange && layout,\n shouldResetStyleCacheOnItemSizeChange && direction\n );\n\n let style;\n if (itemStyleCache.hasOwnProperty(index)) {\n style = itemStyleCache[index];\n } else {\n const offset = getItemOffset(this.props, index, this._instanceProps);\n const size = getItemSize(this.props, index, this._instanceProps);\n\n // TODO Deprecate direction \"horizontal\"\n const isHorizontal =\n direction === 'horizontal' || layout === 'horizontal';\n\n const isRtl = direction === 'rtl';\n const offsetHorizontal = isHorizontal ? offset : 0;\n itemStyleCache[index] = style = {\n position: 'absolute',\n left: isRtl ? undefined : offsetHorizontal,\n right: isRtl ? offsetHorizontal : undefined,\n top: !isHorizontal ? offset : 0,\n height: !isHorizontal ? size : '100%',\n width: isHorizontal ? size : '100%',\n };\n }\n\n return style;\n };\n\n _getItemStyleCache: (_: any, __: any, ___: any) => ItemStyleCache;\n _getItemStyleCache = memoizeOne((_: any, __: any, ___: any) => ({}));\n\n _getRangeToRender(): [number, number, number, number] {\n const { itemCount, overscanCount } = this.props;\n const { isScrolling, scrollDirection, scrollOffset } = this.state;\n\n if (itemCount === 0) {\n return [0, 0, 0, 0];\n }\n\n const startIndex = getStartIndexForOffset(\n this.props,\n scrollOffset,\n this._instanceProps\n );\n const stopIndex = getStopIndexForStartIndex(\n this.props,\n startIndex,\n scrollOffset,\n this._instanceProps\n );\n\n // Overscan by one item in each direction so that tab/focus works.\n // If there isn't at least one extra item, tab loops back around.\n const overscanBackward =\n !isScrolling || scrollDirection === 'backward'\n ? Math.max(1, overscanCount)\n : 1;\n const overscanForward =\n !isScrolling || scrollDirection === 'forward'\n ? Math.max(1, overscanCount)\n : 1;\n\n return [\n Math.max(0, startIndex - overscanBackward),\n Math.max(0, Math.min(itemCount - 1, stopIndex + overscanForward)),\n startIndex,\n stopIndex,\n ];\n }\n\n _onScrollHorizontal = (event: ScrollEvent): void => {\n const { clientWidth, scrollLeft, scrollWidth } = event.currentTarget;\n this.setState(prevState => {\n if (prevState.scrollOffset === scrollLeft) {\n // Scroll position may have been updated by cDM/cDU,\n // In which case we don't need to trigger another render,\n // And we don't want to update state.isScrolling.\n return null;\n }\n\n const { direction } = this.props;\n\n let scrollOffset = scrollLeft;\n if (direction === 'rtl') {\n // TRICKY According to the spec, scrollLeft should be negative for RTL aligned elements.\n // This is not the case for all browsers though (e.g. Chrome reports values as positive, measured relative to the left).\n // It's also easier for this component if we convert offsets to the same format as they would be in for ltr.\n // So the simplest solution is to determine which browser behavior we're dealing with, and convert based on it.\n switch (getRTLOffsetType()) {\n case 'negative':\n scrollOffset = -scrollLeft;\n break;\n case 'positive-descending':\n scrollOffset = scrollWidth - clientWidth - scrollLeft;\n break;\n }\n }\n\n // Prevent Safari's elastic scrolling from causing visual shaking when scrolling past bounds.\n scrollOffset = Math.max(\n 0,\n Math.min(scrollOffset, scrollWidth - clientWidth)\n );\n\n return {\n isScrolling: true,\n scrollDirection:\n prevState.scrollOffset < scrollOffset ? 'forward' : 'backward',\n scrollOffset,\n scrollUpdateWasRequested: false,\n };\n }, this._resetIsScrollingDebounced);\n };\n\n _onScrollVertical = (event: ScrollEvent): void => {\n const { clientHeight, scrollHeight, scrollTop } = event.currentTarget;\n this.setState(prevState => {\n if (prevState.scrollOffset === scrollTop) {\n // Scroll position may have been updated by cDM/cDU,\n // In which case we don't need to trigger another render,\n // And we don't want to update state.isScrolling.\n return null;\n }\n\n // Prevent Safari's elastic scrolling from causing visual shaking when scrolling past bounds.\n const scrollOffset = Math.max(\n 0,\n Math.min(scrollTop, scrollHeight - clientHeight)\n );\n\n return {\n isScrolling: true,\n scrollDirection:\n prevState.scrollOffset < scrollOffset ? 'forward' : 'backward',\n scrollOffset,\n scrollUpdateWasRequested: false,\n };\n }, this._resetIsScrollingDebounced);\n };\n\n _outerRefSetter = (ref: any): void => {\n const { outerRef } = this.props;\n\n this._outerRef = ((ref: any): HTMLDivElement);\n\n if (typeof outerRef === 'function') {\n outerRef(ref);\n } else if (\n outerRef != null &&\n typeof outerRef === 'object' &&\n outerRef.hasOwnProperty('current')\n ) {\n outerRef.current = ref;\n }\n };\n\n _resetIsScrollingDebounced = () => {\n if (this._resetIsScrollingTimeoutId !== null) {\n cancelTimeout(this._resetIsScrollingTimeoutId);\n }\n\n this._resetIsScrollingTimeoutId = requestTimeout(\n this._resetIsScrolling,\n IS_SCROLLING_DEBOUNCE_INTERVAL\n );\n };\n\n _resetIsScrolling = () => {\n this._resetIsScrollingTimeoutId = null;\n\n this.setState({ isScrolling: false }, () => {\n // Clear style cache after state update has been committed.\n // This way we don't break pure sCU for items that don't use isScrolling param.\n this._getItemStyleCache(-1, null);\n });\n };\n };\n}\n\n// NOTE: I considered further wrapping individual items with a pure ListItem component.\n// This would avoid ever calling the render function for the same index more than once,\n// But it would also add the overhead of a lot of components/fibers.\n// I assume people already do this (render function returning a class component),\n// So my doing it would just unnecessarily double the wrappers.\n\nconst validateSharedProps = (\n {\n children,\n direction,\n height,\n layout,\n innerTagName,\n outerTagName,\n width,\n }: Props,\n { instance }: State\n): void => {\n if (process.env.NODE_ENV !== 'production') {\n if (innerTagName != null || outerTagName != null) {\n if (devWarningsTagName && !devWarningsTagName.has(instance)) {\n devWarningsTagName.add(instance);\n console.warn(\n 'The innerTagName and outerTagName props have been deprecated. ' +\n 'Please use the innerElementType and outerElementType props instead.'\n );\n }\n }\n\n // TODO Deprecate direction \"horizontal\"\n const isHorizontal = direction === 'horizontal' || layout === 'horizontal';\n\n switch (direction) {\n case 'horizontal':\n case 'vertical':\n if (devWarningsDirection && !devWarningsDirection.has(instance)) {\n devWarningsDirection.add(instance);\n console.warn(\n 'The direction prop should be either \"ltr\" (default) or \"rtl\". ' +\n 'Please use the layout prop to specify \"vertical\" (default) or \"horizontal\" orientation.'\n );\n }\n break;\n case 'ltr':\n case 'rtl':\n // Valid values\n break;\n default:\n throw Error(\n 'An invalid \"direction\" prop has been specified. ' +\n 'Value should be either \"ltr\" or \"rtl\". ' +\n `\"${direction}\" was specified.`\n );\n }\n\n switch (layout) {\n case 'horizontal':\n case 'vertical':\n // Valid values\n break;\n default:\n throw Error(\n 'An invalid \"layout\" prop has been specified. ' +\n 'Value should be either \"horizontal\" or \"vertical\". ' +\n `\"${layout}\" was specified.`\n );\n }\n\n if (children == null) {\n throw Error(\n 'An invalid \"children\" prop has been specified. ' +\n 'Value should be a React component. ' +\n `\"${children === null ? 'null' : typeof children}\" was specified.`\n );\n }\n\n if (isHorizontal && typeof width !== 'number') {\n throw Error(\n 'An invalid \"width\" prop has been specified. ' +\n 'Horizontal lists must specify a number for width. ' +\n `\"${width === null ? 'null' : typeof width}\" was specified.`\n );\n } else if (!isHorizontal && typeof height !== 'number') {\n throw Error(\n 'An invalid \"height\" prop has been specified. ' +\n 'Vertical lists must specify a number for height. ' +\n `\"${height === null ? 'null' : typeof height}\" was specified.`\n );\n }\n }\n};\n", "// @flow\n\nimport createListComponent from './createListComponent';\n\nimport type { Props, ScrollToAlign } from './createListComponent';\n\nconst DEFAULT_ESTIMATED_ITEM_SIZE = 50;\n\ntype VariableSizeProps = {|\n estimatedItemSize: number,\n ...Props,\n|};\n\ntype itemSizeGetter = (index: number) => number;\n\ntype ItemMetadata = {|\n offset: number,\n size: number,\n|};\ntype InstanceProps = {|\n itemMetadataMap: { [index: number]: ItemMetadata },\n estimatedItemSize: number,\n lastMeasuredIndex: number,\n|};\n\nconst getItemMetadata = (\n props: Props,\n index: number,\n instanceProps: InstanceProps\n): ItemMetadata => {\n const { itemSize } = ((props: any): VariableSizeProps);\n const { itemMetadataMap, lastMeasuredIndex } = instanceProps;\n\n if (index > lastMeasuredIndex) {\n let offset = 0;\n if (lastMeasuredIndex >= 0) {\n const itemMetadata = itemMetadataMap[lastMeasuredIndex];\n offset = itemMetadata.offset + itemMetadata.size;\n }\n\n for (let i = lastMeasuredIndex + 1; i <= index; i++) {\n let size = ((itemSize: any): itemSizeGetter)(i);\n\n itemMetadataMap[i] = {\n offset,\n size,\n };\n\n offset += size;\n }\n\n instanceProps.lastMeasuredIndex = index;\n }\n\n return itemMetadataMap[index];\n};\n\nconst findNearestItem = (\n props: Props,\n instanceProps: InstanceProps,\n offset: number\n) => {\n const { itemMetadataMap, lastMeasuredIndex } = instanceProps;\n\n const lastMeasuredItemOffset =\n lastMeasuredIndex > 0 ? itemMetadataMap[lastMeasuredIndex].offset : 0;\n\n if (lastMeasuredItemOffset >= offset) {\n // If we've already measured items within this range just use a binary search as it's faster.\n return findNearestItemBinarySearch(\n props,\n instanceProps,\n lastMeasuredIndex,\n 0,\n offset\n );\n } else {\n // If we haven't yet measured this high, fallback to an exponential search with an inner binary search.\n // The exponential search avoids pre-computing sizes for the full set of items as a binary search would.\n // The overall complexity for this approach is O(log n).\n return findNearestItemExponentialSearch(\n props,\n instanceProps,\n Math.max(0, lastMeasuredIndex),\n offset\n );\n }\n};\n\nconst findNearestItemBinarySearch = (\n props: Props,\n instanceProps: InstanceProps,\n high: number,\n low: number,\n offset: number\n): number => {\n while (low <= high) {\n const middle = low + Math.floor((high - low) / 2);\n const currentOffset = getItemMetadata(props, middle, instanceProps).offset;\n\n if (currentOffset === offset) {\n return middle;\n } else if (currentOffset < offset) {\n low = middle + 1;\n } else if (currentOffset > offset) {\n high = middle - 1;\n }\n }\n\n if (low > 0) {\n return low - 1;\n } else {\n return 0;\n }\n};\n\nconst findNearestItemExponentialSearch = (\n props: Props,\n instanceProps: InstanceProps,\n index: number,\n offset: number\n): number => {\n const { itemCount } = props;\n let interval = 1;\n\n while (\n index < itemCount &&\n getItemMetadata(props, index, instanceProps).offset < offset\n ) {\n index += interval;\n interval *= 2;\n }\n\n return findNearestItemBinarySearch(\n props,\n instanceProps,\n Math.min(index, itemCount - 1),\n Math.floor(index / 2),\n offset\n );\n};\n\nconst getEstimatedTotalSize = (\n { itemCount }: Props,\n { itemMetadataMap, estimatedItemSize, lastMeasuredIndex }: InstanceProps\n) => {\n let totalSizeOfMeasuredItems = 0;\n\n // Edge case check for when the number of items decreases while a scroll is in progress.\n // https://github.com/bvaughn/react-window/pull/138\n if (lastMeasuredIndex >= itemCount) {\n lastMeasuredIndex = itemCount - 1;\n }\n\n if (lastMeasuredIndex >= 0) {\n const itemMetadata = itemMetadataMap[lastMeasuredIndex];\n totalSizeOfMeasuredItems = itemMetadata.offset + itemMetadata.size;\n }\n\n const numUnmeasuredItems = itemCount - lastMeasuredIndex - 1;\n const totalSizeOfUnmeasuredItems = numUnmeasuredItems * estimatedItemSize;\n\n return totalSizeOfMeasuredItems + totalSizeOfUnmeasuredItems;\n};\n\nconst VariableSizeList = createListComponent({\n getItemOffset: (\n props: Props,\n index: number,\n instanceProps: InstanceProps\n ): number => getItemMetadata(props, index, instanceProps).offset,\n\n getItemSize: (\n props: Props,\n index: number,\n instanceProps: InstanceProps\n ): number => instanceProps.itemMetadataMap[index].size,\n\n getEstimatedTotalSize,\n\n getOffsetForIndexAndAlignment: (\n props: Props,\n index: number,\n align: ScrollToAlign,\n scrollOffset: number,\n instanceProps: InstanceProps,\n scrollbarSize: number\n ): number => {\n const { direction, height, layout, width } = props;\n\n // TODO Deprecate direction \"horizontal\"\n const isHorizontal = direction === 'horizontal' || layout === 'horizontal';\n const size = (((isHorizontal ? width : height): any): number);\n const itemMetadata = getItemMetadata(props, index, instanceProps);\n\n // Get estimated total size after ItemMetadata is computed,\n // To ensure it reflects actual measurements instead of just estimates.\n const estimatedTotalSize = getEstimatedTotalSize(props, instanceProps);\n\n const maxOffset = Math.max(\n 0,\n Math.min(estimatedTotalSize - size, itemMetadata.offset)\n );\n const minOffset = Math.max(\n 0,\n itemMetadata.offset - size + itemMetadata.size + scrollbarSize\n );\n\n if (align === 'smart') {\n if (\n scrollOffset >= minOffset - size &&\n scrollOffset <= maxOffset + size\n ) {\n align = 'auto';\n } else {\n align = 'center';\n }\n }\n\n switch (align) {\n case 'start':\n return maxOffset;\n case 'end':\n return minOffset;\n case 'center':\n return Math.round(minOffset + (maxOffset - minOffset) / 2);\n case 'auto':\n default:\n if (scrollOffset >= minOffset && scrollOffset <= maxOffset) {\n return scrollOffset;\n } else if (scrollOffset < minOffset) {\n return minOffset;\n } else {\n return maxOffset;\n }\n }\n },\n\n getStartIndexForOffset: (\n props: Props,\n offset: number,\n instanceProps: InstanceProps\n ): number => findNearestItem(props, instanceProps, offset),\n\n getStopIndexForStartIndex: (\n props: Props,\n startIndex: number,\n scrollOffset: number,\n instanceProps: InstanceProps\n ): number => {\n const { direction, height, itemCount, layout, width } = props;\n\n // TODO Deprecate direction \"horizontal\"\n const isHorizontal = direction === 'horizontal' || layout === 'horizontal';\n const size = (((isHorizontal ? width : height): any): number);\n const itemMetadata = getItemMetadata(props, startIndex, instanceProps);\n const maxOffset = scrollOffset + size;\n\n let offset = itemMetadata.offset + itemMetadata.size;\n let stopIndex = startIndex;\n\n while (stopIndex < itemCount - 1 && offset < maxOffset) {\n stopIndex++;\n offset += getItemMetadata(props, stopIndex, instanceProps).size;\n }\n\n return stopIndex;\n },\n\n initInstanceProps(props: Props, instance: any): InstanceProps {\n const { estimatedItemSize } = ((props: any): VariableSizeProps);\n\n const instanceProps = {\n itemMetadataMap: {},\n estimatedItemSize: estimatedItemSize || DEFAULT_ESTIMATED_ITEM_SIZE,\n lastMeasuredIndex: -1,\n };\n\n instance.resetAfterIndex = (\n index: number,\n shouldForceUpdate?: boolean = true\n ) => {\n instanceProps.lastMeasuredIndex = Math.min(\n instanceProps.lastMeasuredIndex,\n index - 1\n );\n\n // We could potentially optimize further by only evicting styles after this index,\n // But since styles are only cached while scrolling is in progress-\n // It seems an unnecessary optimization.\n // It's unlikely that resetAfterIndex() will be called while a user is scrolling.\n instance._getItemStyleCache(-1);\n\n if (shouldForceUpdate) {\n instance.forceUpdate();\n }\n };\n\n return instanceProps;\n },\n\n shouldResetStyleCacheOnItemSizeChange: false,\n\n validateProps: ({ itemSize }: Props): void => {\n if (process.env.NODE_ENV !== 'production') {\n if (typeof itemSize !== 'function') {\n throw Error(\n 'An invalid \"itemSize\" prop has been specified. ' +\n 'Value should be a function. ' +\n `\"${itemSize === null ? 'null' : typeof itemSize}\" was specified.`\n );\n }\n }\n },\n});\n\nexport default VariableSizeList;\n", "// @flow\n\nimport createGridComponent from './createGridComponent';\n\nimport type { Props, ScrollToAlign } from './createGridComponent';\n\nconst FixedSizeGrid = createGridComponent({\n getColumnOffset: ({ columnWidth }: Props, index: number): number =>\n index * ((columnWidth: any): number),\n\n getColumnWidth: ({ columnWidth }: Props, index: number): number =>\n ((columnWidth: any): number),\n\n getRowOffset: ({ rowHeight }: Props, index: number): number =>\n index * ((rowHeight: any): number),\n\n getRowHeight: ({ rowHeight }: Props, index: number): number =>\n ((rowHeight: any): number),\n\n getEstimatedTotalHeight: ({ rowCount, rowHeight }: Props) =>\n ((rowHeight: any): number) * rowCount,\n\n getEstimatedTotalWidth: ({ columnCount, columnWidth }: Props) =>\n ((columnWidth: any): number) * columnCount,\n\n getOffsetForColumnAndAlignment: (\n { columnCount, columnWidth, width }: Props,\n columnIndex: number,\n align: ScrollToAlign,\n scrollLeft: number,\n instanceProps: typeof undefined,\n scrollbarSize: number\n ): number => {\n const lastColumnOffset = Math.max(\n 0,\n columnCount * ((columnWidth: any): number) - width\n );\n const maxOffset = Math.min(\n lastColumnOffset,\n columnIndex * ((columnWidth: any): number)\n );\n const minOffset = Math.max(\n 0,\n columnIndex * ((columnWidth: any): number) -\n width +\n scrollbarSize +\n ((columnWidth: any): number)\n );\n\n if (align === 'smart') {\n if (scrollLeft >= minOffset - width && scrollLeft <= maxOffset + width) {\n align = 'auto';\n } else {\n align = 'center';\n }\n }\n\n switch (align) {\n case 'start':\n return maxOffset;\n case 'end':\n return minOffset;\n case 'center':\n // \"Centered\" offset is usually the average of the min and max.\n // But near the edges of the list, this doesn't hold true.\n const middleOffset = Math.round(\n minOffset + (maxOffset - minOffset) / 2\n );\n if (middleOffset < Math.ceil(width / 2)) {\n return 0; // near the beginning\n } else if (middleOffset > lastColumnOffset + Math.floor(width / 2)) {\n return lastColumnOffset; // near the end\n } else {\n return middleOffset;\n }\n case 'auto':\n default:\n if (scrollLeft >= minOffset && scrollLeft <= maxOffset) {\n return scrollLeft;\n } else if (minOffset > maxOffset) {\n // Because we only take into account the scrollbar size when calculating minOffset\n // this value can be larger than maxOffset when at the end of the list\n return minOffset;\n } else if (scrollLeft < minOffset) {\n return minOffset;\n } else {\n return maxOffset;\n }\n }\n },\n\n getOffsetForRowAndAlignment: (\n { rowHeight, height, rowCount }: Props,\n rowIndex: number,\n align: ScrollToAlign,\n scrollTop: number,\n instanceProps: typeof undefined,\n scrollbarSize: number\n ): number => {\n const lastRowOffset = Math.max(\n 0,\n rowCount * ((rowHeight: any): number) - height\n );\n const maxOffset = Math.min(\n lastRowOffset,\n rowIndex * ((rowHeight: any): number)\n );\n const minOffset = Math.max(\n 0,\n rowIndex * ((rowHeight: any): number) -\n height +\n scrollbarSize +\n ((rowHeight: any): number)\n );\n\n if (align === 'smart') {\n if (scrollTop >= minOffset - height && scrollTop <= maxOffset + height) {\n align = 'auto';\n } else {\n align = 'center';\n }\n }\n\n switch (align) {\n case 'start':\n return maxOffset;\n case 'end':\n return minOffset;\n case 'center':\n // \"Centered\" offset is usually the average of the min and max.\n // But near the edges of the list, this doesn't hold true.\n const middleOffset = Math.round(\n minOffset + (maxOffset - minOffset) / 2\n );\n if (middleOffset < Math.ceil(height / 2)) {\n return 0; // near the beginning\n } else if (middleOffset > lastRowOffset + Math.floor(height / 2)) {\n return lastRowOffset; // near the end\n } else {\n return middleOffset;\n }\n case 'auto':\n default:\n if (scrollTop >= minOffset && scrollTop <= maxOffset) {\n return scrollTop;\n } else if (minOffset > maxOffset) {\n // Because we only take into account the scrollbar size when calculating minOffset\n // this value can be larger than maxOffset when at the end of the list\n return minOffset;\n } else if (scrollTop < minOffset) {\n return minOffset;\n } else {\n return maxOffset;\n }\n }\n },\n\n getColumnStartIndexForOffset: (\n { columnWidth, columnCount }: Props,\n scrollLeft: number\n ): number =>\n Math.max(\n 0,\n Math.min(\n columnCount - 1,\n Math.floor(scrollLeft / ((columnWidth: any): number))\n )\n ),\n\n getColumnStopIndexForStartIndex: (\n { columnWidth, columnCount, width }: Props,\n startIndex: number,\n scrollLeft: number\n ): number => {\n const left = startIndex * ((columnWidth: any): number);\n const numVisibleColumns = Math.ceil(\n (width + scrollLeft - left) / ((columnWidth: any): number)\n );\n return Math.max(\n 0,\n Math.min(\n columnCount - 1,\n startIndex + numVisibleColumns - 1 // -1 is because stop index is inclusive\n )\n );\n },\n\n getRowStartIndexForOffset: (\n { rowHeight, rowCount }: Props,\n scrollTop: number\n ): number =>\n Math.max(\n 0,\n Math.min(rowCount - 1, Math.floor(scrollTop / ((rowHeight: any): number)))\n ),\n\n getRowStopIndexForStartIndex: (\n { rowHeight, rowCount, height }: Props,\n startIndex: number,\n scrollTop: number\n ): number => {\n const top = startIndex * ((rowHeight: any): number);\n const numVisibleRows = Math.ceil(\n (height + scrollTop - top) / ((rowHeight: any): number)\n );\n return Math.max(\n 0,\n Math.min(\n rowCount - 1,\n startIndex + numVisibleRows - 1 // -1 is because stop index is inclusive\n )\n );\n },\n\n initInstanceProps(props: Props): any {\n // Noop\n },\n\n shouldResetStyleCacheOnItemSizeChange: true,\n\n validateProps: ({ columnWidth, rowHeight }: Props): void => {\n if (process.env.NODE_ENV !== 'production') {\n if (typeof columnWidth !== 'number') {\n throw Error(\n 'An invalid \"columnWidth\" prop has been specified. ' +\n 'Value should be a number. ' +\n `\"${\n columnWidth === null ? 'null' : typeof columnWidth\n }\" was specified.`\n );\n }\n\n if (typeof rowHeight !== 'number') {\n throw Error(\n 'An invalid \"rowHeight\" prop has been specified. ' +\n 'Value should be a number. ' +\n `\"${rowHeight === null ? 'null' : typeof rowHeight}\" was specified.`\n );\n }\n }\n },\n});\n\nexport default FixedSizeGrid;\n", "// @flow\n\nimport createListComponent from './createListComponent';\n\nimport type { Props, ScrollToAlign } from './createListComponent';\n\ntype InstanceProps = any;\n\nconst FixedSizeList = createListComponent({\n getItemOffset: ({ itemSize }: Props, index: number): number =>\n index * ((itemSize: any): number),\n\n getItemSize: ({ itemSize }: Props, index: number): number =>\n ((itemSize: any): number),\n\n getEstimatedTotalSize: ({ itemCount, itemSize }: Props) =>\n ((itemSize: any): number) * itemCount,\n\n getOffsetForIndexAndAlignment: (\n { direction, height, itemCount, itemSize, layout, width }: Props,\n index: number,\n align: ScrollToAlign,\n scrollOffset: number,\n instanceProps: InstanceProps,\n scrollbarSize: number\n ): number => {\n // TODO Deprecate direction \"horizontal\"\n const isHorizontal = direction === 'horizontal' || layout === 'horizontal';\n const size = (((isHorizontal ? width : height): any): number);\n const lastItemOffset = Math.max(\n 0,\n itemCount * ((itemSize: any): number) - size\n );\n const maxOffset = Math.min(\n lastItemOffset,\n index * ((itemSize: any): number)\n );\n const minOffset = Math.max(\n 0,\n index * ((itemSize: any): number) -\n size +\n ((itemSize: any): number) +\n scrollbarSize\n );\n\n if (align === 'smart') {\n if (\n scrollOffset >= minOffset - size &&\n scrollOffset <= maxOffset + size\n ) {\n align = 'auto';\n } else {\n align = 'center';\n }\n }\n\n switch (align) {\n case 'start':\n return maxOffset;\n case 'end':\n return minOffset;\n case 'center': {\n // \"Centered\" offset is usually the average of the min and max.\n // But near the edges of the list, this doesn't hold true.\n const middleOffset = Math.round(\n minOffset + (maxOffset - minOffset) / 2\n );\n if (middleOffset < Math.ceil(size / 2)) {\n return 0; // near the beginning\n } else if (middleOffset > lastItemOffset + Math.floor(size / 2)) {\n return lastItemOffset; // near the end\n } else {\n return middleOffset;\n }\n }\n case 'auto':\n default:\n if (scrollOffset >= minOffset && scrollOffset <= maxOffset) {\n return scrollOffset;\n } else if (scrollOffset < minOffset) {\n return minOffset;\n } else {\n return maxOffset;\n }\n }\n },\n\n getStartIndexForOffset: (\n { itemCount, itemSize }: Props,\n offset: number\n ): number =>\n Math.max(\n 0,\n Math.min(itemCount - 1, Math.floor(offset / ((itemSize: any): number)))\n ),\n\n getStopIndexForStartIndex: (\n { direction, height, itemCount, itemSize, layout, width }: Props,\n startIndex: number,\n scrollOffset: number\n ): number => {\n // TODO Deprecate direction \"horizontal\"\n const isHorizontal = direction === 'horizontal' || layout === 'horizontal';\n const offset = startIndex * ((itemSize: any): number);\n const size = (((isHorizontal ? width : height): any): number);\n const numVisibleItems = Math.ceil(\n (size + scrollOffset - offset) / ((itemSize: any): number)\n );\n return Math.max(\n 0,\n Math.min(\n itemCount - 1,\n startIndex + numVisibleItems - 1 // -1 is because stop index is inclusive\n )\n );\n },\n\n initInstanceProps(props: Props): any {\n // Noop\n },\n\n shouldResetStyleCacheOnItemSizeChange: true,\n\n validateProps: ({ itemSize }: Props): void => {\n if (process.env.NODE_ENV !== 'production') {\n if (typeof itemSize !== 'number') {\n throw Error(\n 'An invalid \"itemSize\" prop has been specified. ' +\n 'Value should be a number. ' +\n `\"${itemSize === null ? 'null' : typeof itemSize}\" was specified.`\n );\n }\n }\n },\n});\n\nexport default FixedSizeList;\n", "// @flow\n\n// Pulled from react-compat\n// https://github.com/developit/preact-compat/blob/7c5de00e7c85e2ffd011bf3af02899b63f699d3a/src/index.js#L349\nexport default function shallowDiffers(prev: Object, next: Object): boolean {\n for (let attribute in prev) {\n if (!(attribute in next)) {\n return true;\n }\n }\n for (let attribute in next) {\n if (prev[attribute] !== next[attribute]) {\n return true;\n }\n }\n return false;\n}\n", "// @flow\n\nimport shallowDiffers from './shallowDiffers';\n\n// Custom comparison function for React.memo().\n// It knows to compare individual style props and ignore the wrapper object.\n// See https://reactjs.org/docs/react-api.html#reactmemo\nexport default function areEqual(\n prevProps: Object,\n nextProps: Object\n): boolean {\n const { style: prevStyle, ...prevRest } = prevProps;\n const { style: nextStyle, ...nextRest } = nextProps;\n\n return (\n !shallowDiffers(prevStyle, nextStyle) && !shallowDiffers(prevRest, nextRest)\n );\n}\n", "// @flow\n\nimport areEqual from './areEqual';\nimport shallowDiffers from './shallowDiffers';\n\n// Custom shouldComponentUpdate for class components.\n// It knows to compare individual style props and ignore the wrapper object.\n// See https://reactjs.org/docs/react-component.html#shouldcomponentupdate\nexport default function shouldComponentUpdate(\n nextProps: Object,\n nextState: Object\n): boolean {\n return (\n !areEqual(this.props, nextProps) || shallowDiffers(this.state, nextState)\n );\n}\n", "import React from \"react\";\nimport {connect} from \"react-redux\";\nimport memoizeOne from \"memoize-one\";\nimport AutoSizer from \"react-virtualized-auto-sizer\";\nimport {FixedSizeList, areEqual} from \"react-window\";\nimport {Lot} from \"@nextlot/core/webcast/data/data_types_definitions\";\nimport {LOT_STATES_MAP, ROUND_TYPES_DISPLAY_NAMES_MAP, RoundTypeEnum} from \"@nextlot/core/webcast/data/WebcastDataDomain\";\nimport {TaggedLogger} from \"@nextlot/core/utilities\";\nimport {AuctionsManager} from \"@nextlot/core/webcast\";\nimport {ReduxStateType} from \"@nextlot/core/webcast/services/DataStore\";\nimport {ReduxWebcastAuctionDataType} from \"@nextlot/core/webcast/redux/webcast/reducerWebcastAuctionData\";\n\n\ntype LotListItemDataType = {\n lots: Array,\n selectedLotsIds: Array,\n currentRoundLotsIds: Array,\n filteredLotsIds: Array,\n onClickLotItem: (itemIndex: number, lots:Array)=>any,\n}\n\n\ntype LotListItemPropsType = {\n data: LotListItemDataType,\n index: number,\n style: {}\n};\n\n\n// React.memo acts as a PureComponent here (https://reactjs.org/blog/2018/10/23/react-v-16-6.html#reactmemo)\nfunction LotListItemMemoCmp(props: LotListItemPropsType) {\n const {index, style} = props;\n const itemData: LotListItemDataType = props.data;\n const currentRoundLotsIds = itemData.currentRoundLotsIds || [];\n const lot: Lot = itemData.lots[index];\n let lotId;\n\n if (lot) {\n lotId = lot.id;\n }\n\n const isThisLotSelected = itemData.selectedLotsIds && itemData.selectedLotsIds.indexOf(lotId) > -1;\n\n if (lot) {\n return (\n -1) ? 'current-round' : ''}`}\n style={style}>\n
\n
{lot.number}  
\n
{lot.name}
\n
({LOT_STATES_MAP.get(lot.state)})
\n
\n {`Lot\n
\n )\n } else {\n return false;\n }\n}\n\n// @ts-ignore\nconst LotListItem = React.memo(LotListItemMemoCmp, areEqual);\n\n\nconst createLotsListItemData = memoizeOne((lots, selectedLotsIds, currentRoundLotsIds, onClickLotItem) => ({\n lots,\n currentRoundLotsIds,\n selectedLotsIds,\n onClickLotItem,\n}));\n\n\nconst _logger = TaggedLogger.get('ClerkLotsListCmp');\n\n\ntype CmpPropsType = {\n webcastAuctionData: ReduxWebcastAuctionDataType,\n currentRoundLotsIds: Array,\n enableRoundActions: boolean,\n};\n\ntype CmpStateType = Partial<{\n selectedLotsIds: Array,\n lastSelectedLotsListIndex: number,\n filteredLots: Array,\n hiddenClosedLots: boolean,\n}>\n\n\nclass ClerkLotsListCmp extends React.Component {\n\n constructor(props) {\n super(props);\n\n this.state = {\n selectedLotsIds: [],\n lastSelectedLotsListIndex: 0,\n filteredLots: [],\n hiddenClosedLots: false\n }\n }\n\n\n handleOnLotItemClick = (itemIndex: number, lots) => (evt) => {\n _logger.debug('.handleClick_LotsListItem: evt: ctrl:', evt.ctrlKey, 'shift:', evt.shiftKey, 'meta:', evt.metaKey, 'alt:', evt.altKey);\n\n let newSelectedLotsIds;\n let lastSelectedLotsListIndex: number = this.state.lastSelectedLotsListIndex;\n let lotId: number = lots[itemIndex].id;\n\n\n if (evt.shiftKey) {\n const l1 = Math.min(lastSelectedLotsListIndex, itemIndex);\n const l2 = Math.max(lastSelectedLotsListIndex, itemIndex);\n\n const shiftSelectedLotsIts = [];\n for (let i = l1; i <= l2; i += 1) {\n shiftSelectedLotsIts.push(lots[i].id);\n }\n\n newSelectedLotsIds = [...this.state.selectedLotsIds, ...shiftSelectedLotsIts];\n } else if (evt.altKey || evt.metaKey) {\n if (this.state.selectedLotsIds.includes(lotId)) {\n newSelectedLotsIds = this.state.selectedLotsIds.filter((lId) => lotId !== lId);\n } else {\n newSelectedLotsIds = [...this.state.selectedLotsIds, lotId];\n lastSelectedLotsListIndex = itemIndex;\n }\n } else {\n if (this.state.selectedLotsIds.includes(lotId)) {\n if (this.state.selectedLotsIds.length > 1) {\n newSelectedLotsIds = [lotId];\n lastSelectedLotsListIndex = itemIndex;\n } else {\n newSelectedLotsIds = [];\n }\n } else {\n newSelectedLotsIds = [lotId];\n lastSelectedLotsListIndex = itemIndex;\n }\n }\n\n this.setState({\n selectedLotsIds: newSelectedLotsIds,\n lastSelectedLotsListIndex,\n });\n };\n\n handleDblClick_Pass = () => {\n const lotsIds = [... new Set(this.state.selectedLotsIds)];\n AuctionsManager.currentWebcastAuctionHandler.controller.sendLotsPass(lotsIds);\n };\n\n\n handleClick_RoundCreate = (roundType) => {\n const lotsIds = [... new Set(this.state.selectedLotsIds)];\n AuctionsManager.currentWebcastAuctionHandler.controller.sendRoundCreate(roundType, lotsIds);\n };\n\n handleOnChange = (event) => {\n const webcastAuctionData: ReduxWebcastAuctionDataType = this.props.webcastAuctionData;\n let lots;\n\n if (this.state.hiddenClosedLots) {\n lots = webcastAuctionData.lots.map(lot => lot).filter(l => l.state === -1);\n } else {\n lots = webcastAuctionData.lots;\n }\n\n let filteredLots = [];\n let filterLotsArray;\n let results = event.target.value.toLowerCase().split(\",\"); // split expression separated by \",\"\n\n for (let i in results) {\n let searchTextString = results[i].trim();\n if (searchTextString.length > 0) { //it's not an empty string\n // check if interval\n if (searchTextString.indexOf('-') > 0) {\n const results2 = searchTextString.split(\"-\");\n\n // accept it only if it has 2 bounds\n if (results2.length === 2) {\n let lot1 = lots.map(lot => lot).filter(l => l.number.toLowerCase() === results2[0].toLowerCase())[0];\n\n if (lot1) {\n let lot2 = lots.map(lot => lot).filter(l => l.number.toLowerCase() === results2[1].toLowerCase())[0];\n\n if (lot2) {\n if (lot1.sortIdx < lot2.sortIdx) {\n lots.map(lot => {\n if (lot.sortIdx >= lot1.sortIdx && lot.sortIdx <= lot2.sortIdx) {\n filteredLots = [...filteredLots, ...lot].filter(el => el != null);\n }\n });\n }\n }\n }\n }\n } else {\n // it's not an interval\n let lot1 = lots.map(lot => lot).filter(l => l.number.toLowerCase() === searchTextString);\n filteredLots = [...filteredLots, ...lot1].filter(el => el != null);\n }\n }\n }\n // sorted array with all filtered lots\n filterLotsArray = filteredLots.filter((item, index) => filteredLots.indexOf(item) === index).sort((a, b) => a.sortIdx > b.sortIdx ? 1 : -1);\n\n this.setState({\n filteredLots: filterLotsArray\n });\n };\n\n handleChange_HideClosedLots = () => {\n this.setState(state => ({\n hiddenClosedLots: !state.hiddenClosedLots\n }));\n };\n\n _renderActionsButtons() {\n if (this.state.selectedLotsIds.length === 0) {\n // nothing selected\n return null\n }\n\n const buttonsDefs = [];\n\n if (this.state.selectedLotsIds.length === 1) {\n const itemsQty = this.props.webcastAuctionData.lotsMapById.get(this.state.selectedLotsIds[0]).itemsQty;\n if (itemsQty > 1) {\n buttonsDefs.push({\n label: ROUND_TYPES_DISPLAY_NAMES_MAP.get(RoundTypeEnum.SINGLE_NORMAL),\n roundType: RoundTypeEnum.SINGLE_NORMAL,\n });\n\n buttonsDefs.push({\n label: ROUND_TYPES_DISPLAY_NAMES_MAP.get(RoundTypeEnum.SINGLE_BOXLOT),\n roundType: RoundTypeEnum.SINGLE_BOXLOT,\n });\n } else {\n buttonsDefs.push({\n label: ROUND_TYPES_DISPLAY_NAMES_MAP.get(RoundTypeEnum.SINGLE_NORMAL),\n roundType: RoundTypeEnum.SINGLE_NORMAL,\n });\n }\n\n } else {\n buttonsDefs.push({\n label: ROUND_TYPES_DISPLAY_NAMES_MAP.get(RoundTypeEnum.GROUP_CHOICE),\n roundType: RoundTypeEnum.GROUP_CHOICE,\n });\n\n buttonsDefs.push({\n label: ROUND_TYPES_DISPLAY_NAMES_MAP.get(RoundTypeEnum.GROUP_ONEMONEY),\n roundType: RoundTypeEnum.GROUP_ONEMONEY,\n });\n\n buttonsDefs.push({\n label: ROUND_TYPES_DISPLAY_NAMES_MAP.get(RoundTypeEnum.GROUP_TIMESTHEMONEY),\n roundType: RoundTypeEnum.GROUP_TIMESTHEMONEY,\n });\n }\n\n\n return (\n
\n {buttonsDefs.map((btnDef) => {\n return ;\n })}\n\n\n \n
\n )\n }\n\n\n render() {\n _logger.debug('.render()', this.props);\n const webcastAuctionData: ReduxWebcastAuctionDataType = this.props.webcastAuctionData;\n let lots;\n\n if (this.state.filteredLots.length > 0) {\n // check if are lots that are matching the search\n if (this.state.hiddenClosedLots) {\n lots = this.state.filteredLots.map(lot => lot).filter(l => l.state === -1);\n } else {\n lots = this.state.filteredLots;\n }\n } else {\n // all the lots\n if (this.state.hiddenClosedLots) {\n // only open lots\n lots = webcastAuctionData.lots.map(lot => lot).filter(l => l.state === -1);\n } else {\n lots = webcastAuctionData.lots;\n }\n }\n\n const itemData = createLotsListItemData(lots, this.state.selectedLotsIds, this.props.currentRoundLotsIds, this.handleOnLotItemClick);\n\n return (\n
\n\n
\n
\n Filter by Lot #  \n \n
\n\n {this.props.enableRoundActions && this._renderActionsButtons()}\n
\n\n\n
\n \n {({height, width}) => (\n itemData.lots[index] ? itemData.lots[index].id : Math.random()}\n >\n {LotListItem}\n \n )}\n \n
\n\n
\n \n {lots.length} Lots\n \n \n
\n\n
\n );\n }\n}\n\n\nexport default connect(({activeWebcast}: ReduxStateType) => {\n return {\n webcastAuctionData: activeWebcast.webcastAuctionData,\n currentRoundLotsIds: activeWebcast.webcastCurrentRound.lotsIds,\n enableRoundActions: activeWebcast.webcastStatus.biddingFunctionsEnabled && !(activeWebcast.webcastCurrentRoundBidding.askingBidValue > 0 || activeWebcast.webcastCurrentRoundBidding.highestBid),\n };\n})(ClerkLotsListCmp);\n\n\n", "import React from \"react\";\nimport {connect} from \"react-redux\";\nimport {Lot} from \"@nextlot/core/webcast/data/data_types_definitions\";\nimport {ROUND_TYPES_MAP} from \"@nextlot/core/webcast/data/WebcastDataDomain\";\nimport {ReduxWebcastCurrentRoundType} from \"@nextlot/core/webcast/redux/webcast/reducerWebcastCurrentRound\";\nimport {ReduxStateType} from \"@nextlot/core/webcast/services/DataStore\";\n\n\ntype CurrentRoundLotListItemPropsType = {\n lot: Partial\n}\n\nconst CurrentRoundLotListItem = (props:CurrentRoundLotListItemPropsType) => {\n const { lot } = props;\n\n return (\n
  • \n {`Lot\n
    {lot.number}
    \n
    {lot.name}
    \n
  • \n )\n};\n\n\n\n\n\ntype ClerkCurrentRoundCmpPropsType = {\n webcastCurrentRound: ReduxWebcastCurrentRoundType,\n\n lotsMapById: Map,\n};\n\nconst ClerkCurrentRoundCmp = (props:ClerkCurrentRoundCmpPropsType) => {\n return (\n
    \n
    \n Round: {ROUND_TYPES_MAP.get(props.webcastCurrentRound.roundType)} [{props.webcastCurrentRound.lotsIds.length}]\n
    \n
    \n
    \n
      \n {props.webcastCurrentRound.lotsIds.map ((lotId) => {\n const lot = props.lotsMapById.get(lotId);\n return \n })}\n
    \n
    \n
    \n
    \n )\n};\n\n\n\n\n\n\n\nexport default connect(({ activeWebcast }:ReduxStateType) => {\n return {\n webcastCurrentRound: activeWebcast.webcastCurrentRound,\n lotsMapById: activeWebcast.webcastAuctionData.lotsMapById\n };\n})(ClerkCurrentRoundCmp);\n", "import React from \"react\";\nimport NumberDisplay from \"../NumberDisplay\";\nimport {TaggedLogger} from \"@nextlot/core/utilities\";\nimport {Bid} from \"@nextlot/core/webcast/data/data_types_definitions\";\nimport {AuctionsManager} from \"@nextlot/core/webcast\";\nimport {useAppSelector} from \"@nextlot/core/webcast/hooks\";\n\nconst _logger = TaggedLogger.get('ClerkBiddingHistoryCmp');\n\n\nfunction BiddingHistoryListItem(props:{bid:Bid, isHighestBid:boolean, isInternetBidder:boolean}) {\n return (\n
    \n
    {NumberDisplay.formatValueCents(props.bid.value)}
    \n
    {props.bid.bidderDisplay} {props.bid.auto ? '*' : null}
    \n
    \n )\n}\n\n\nexport default function ClerkBiddingHistoryCmp() {\n\n const myUserId:number = AuctionsManager.currentWebcastAuctionHandler.auctionConnectData.participantId;\n const bidsHistory = useAppSelector((state) => state.activeWebcast.webcastCurrentRoundBidding.bidsHistory);\n\n return (\n
    \n
    \n Bidding History\n
    \n\n
    \n { bidsHistory && bidsHistory.length > 0 &&\n\n
    \n {\n [... bidsHistory] // clone Array so we do not mutate with .reverse()\n .reverse()\n .map((bid, index) => ())\n\n }\n
    \n }\n
    \n
    \n )\n}\n", "import React from \"react\";\nimport {useAppSelector} from \"@nextlot/core/webcast/hooks\";\n\n\nexport default function NetworkDisconnectedAlertPanelOverlayCmp() {\n\n const wbsNetworkConnectionState = useAppSelector(reduxState => reduxState.activeWebcast.wbsNetworkStatus.connectionState);\n\n const [reloadPageInProgress, setReloadPageInProgress] = React.useState(false);\n\n const handleClick_ReloadPageButton = (evt) => {\n setReloadPageInProgress(true);\n window.location.reload();\n };\n\n\n if (wbsNetworkConnectionState > 0) {\n // don't render anything if connected or connect is in progress\n return null;\n }\n\n return (\n
    \n
    \n

    Network error

    \n

    Oops...You were unable to connect to the Webcast!

    \n

    This may be because:

    \n

    - You left your browser on your mobile device and will be required to refresh when returning to the auction.

    \n

    - You are no longer connected to the internet.

    \n

    - The auction company has not started the auction. Please check back in a few minutes.

    \n

    - A firewall is blocking outgoing port 443 (HTTPS). Please get in touch with your IT contact to\n have them open port 443 (HTTPS) on your router.

    \n

    \n\n

    You can try to reload the page and this will attempt to reconnect.

    \n\n
    \n \n {reloadPageInProgress && }\n
    \n
    \n
    \n )\n}\n\n", "import * as luxon from \"luxon\";\nimport {IPusherAdapter} from \"./services/IPusherAdapter\";\nimport {TaggedLogger, TimerEventsEmitter} from \"./utilities\";\nimport {CurrentBidder} from \"./type_defs/model\";\nimport {AppRemoteDataHandler} from \"./services/AppRemoteDataHandler\";\nimport {LotsViewModes_Enum} from \"./rematch/models/currentAuctionLotsModel\";\n\n\nconst _logger = TaggedLogger.get('AppController');\n\n\ntype AppConfig_TypeDef = {\n site_id: number,\n frontend_api_base_url: string,\n\n site_timezone_name: string,\n\n site_initial_catalog_lots_view_mode?: LotsViewModes_Enum,\n\n bidder_id?: number,\n bidder_email?: string,\n bidder_token?: string,\n}\n\ntype InitArgs_TypeDef = {\n appConfig: AppConfig_TypeDef,\n pusherAdapter?:IPusherAdapter,\n onAuthenticationRemoved?:()=>void,\n}\n\n\nexport default class AppController {\n public static instance:AppController|null = null;\n\n public static init = async (initArgs:InitArgs_TypeDef):Promise => {\n if (AppController.instance) {\n throw 'AppController.init: already initialized';\n }\n\n luxon.Settings.defaultZone = initArgs.appConfig.site_timezone_name;\n if (initArgs.appConfig.site_timezone_name.toLowerCase().startsWith('australia')) {\n luxon.Settings.defaultLocale = 'en-AU';\n }\n\n AppController.instance = new AppController(initArgs);\n\n await AppController.instance.initServices();\n\n ((window || global || {}) as any)._dev_AppController_instance = AppController.instance;\n\n return AppController.instance;\n }\n\n\n\n public readonly appConfig:AppConfig_TypeDef;\n public readonly remoteDataHandler: AppRemoteDataHandler;\n public readonly timerEventsEmitter: TimerEventsEmitter;\n public readonly remoteEventsEmitter: IPusherAdapter;\n private readonly _handleAuthenticationRemoved: () => void;\n private _currentBidder: CurrentBidder|null;\n\n\n\n constructor({ appConfig, pusherAdapter, onAuthenticationRemoved }:InitArgs_TypeDef) {\n if (AppController.instance) {\n throw new Error('AppController.new: already initialized');\n }\n _logger.debug('.constructor: ', appConfig);\n\n this.appConfig = appConfig;\n\n this.remoteDataHandler = new AppRemoteDataHandler({\n frontendApiBaseUrl: this.appConfig.frontend_api_base_url,\n siteId: this.appConfig.site_id,\n });\n\n this.remoteEventsEmitter = pusherAdapter;\n this.timerEventsEmitter = TimerEventsEmitter.init();\n\n this._handleAuthenticationRemoved = () => {\n this._setCurrentBidder(null);\n this.remoteEventsEmitter?.updateCurrentBidder(null);\n onAuthenticationRemoved && onAuthenticationRemoved();\n }\n\n this.remoteDataHandler.onAuthenticationStateChanged((isAuthenticated) => {\n if (! isAuthenticated) {\n _logger.warn('Authentication lost! Most likely the Api Bidder Token was invalidated remotely or expired.');\n this._handleAuthenticationRemoved();\n }\n });\n\n this.remoteDataHandler.onResponseSuccess(({ headers }) => {\n const httpDate:string = headers['date'];\n this.timerEventsEmitter.updateServerUnixTimestamp(new Date(httpDate).getTime() / 1_000);\n });\n }\n\n private _setCurrentBidder(currentBidder:CurrentBidder|null) {\n this._currentBidder = currentBidder?.id ? currentBidder : null;\n }\n\n public get currentBidder():null|CurrentBidder {\n // this is an intentional *hack* to use the stored value `this._currentBidder` from AppController\n // it's irrelevant if the value for `AppController.currentBidder` will change, because if it does, then\n // it is handled by the app registered callback in AppController.init for `onAuthenticationRemoved`\n // This will be re-addressed when we need to respond to change of `currentBidder` in the views (like maybe on mobile app?)\n return this._currentBidder;\n }\n\n\n async initServices() {\n _logger.debug('.initServices() ...');\n\n const isValidBidderToken = await this.remoteDataHandler.setAndAsyncRemoteVerifyBidderToken(this.appConfig.bidder_token);\n if (isValidBidderToken) {\n this._setCurrentBidder({\n id: this.appConfig.bidder_id,\n email: this.appConfig.bidder_email,\n apiToken: this.appConfig.bidder_token,\n });\n }\n\n await this.remoteEventsEmitter?.init(this.currentBidder);\n\n _logger.info('.initServices() DONE.');\n }\n\n\n\n\n async destroy() {\n await this.remoteEventsEmitter?.disconnect();\n }\n\n}\n", "\nexport const PusherChannelNames = {\n publicEventsForSiteAuctions: function(siteId:number) {\n return `pub-s${siteId}-a`;\n },\n\n publicEventsForAuctionLots: function(siteId:number, auctionId:number) {\n return `pub-s${siteId}-a${auctionId}-l`;\n },\n\n privateEventsForBidder: function(siteId:number, bidderId:number) {\n return `private-s${siteId}-b${bidderId}`;\n }\n}\n\n\nexport enum PusherConnectionStatesEnum {\n connected = 'connected',\n connecting = 'connecting',\n failed = 'failed',\n unavailable = 'unavailable',\n disconnected = 'disconnected',\n}\n\nexport interface IPusherAdapter {\n init(currentBidder?:{ id:number, apiToken:string }):Promise;\n\n updateCurrentBidder(bidder?:false|null|{id:number, token:string}):void;\n\n connect(): Promise;\n disconnect(): Promise;\n\n onConnectionError(callbackFn:()=>void):()=>void;\n onConnectionStateChange(callbackFn:(currentState:PusherConnectionStatesEnum, previousState:PusherConnectionStatesEnum)=>void):()=>void;\n\n onAuctionVisibilityChange(callbackFn:(data:{ auctionId:number, isVisible:boolean })=>void):()=>void;\n onAuctionDescriptiveChange(callbackFn:(data:{ auctionId:number })=>void):()=>void;\n onAuctionBiddingWarrantStateChange(callbackFn:(data:{ auctionId:number, state:string })=>void):()=>void;\n\n onAuctionLotsChange(auctionId:number, callbackFn:(data:{ lotId:number })=>void):()=>void;\n onMyLotsInterestChange(callbackFn:(data:{ auctionId: number, lotId: number, isWatched:boolean })=>void);\n}\n\n", "import React from \"react\";\nimport {useDispatch, useSelector} from \"react-redux\"\nimport {Dispatch, RootState} from \"../rematch/store\";\nimport AppController from \"../AppController\";\nimport {TaggedLogger} from \"../utilities\";\nimport {AuctionsModelListSubState, AuctionsModelState} from \"../rematch/models/auctionsListsModel\";\nimport { ListingBrowserParams } from \"type_defs/model\";\n\n\nconst _logger = TaggedLogger.get('AuctionsListHook');\n\n\nexport function useLoadActiveAuctionsList(browserParams: ListingBrowserParams, loadOnFirstRender:boolean = false):[AuctionsModelListSubState, ()=>void] {\n const auctionsList = useSelector((state: RootState) => state.auctionsLists.active);\n const dispatch = useDispatch();\n\n const loadAuctionsList = React.useCallback(dispatch.auctionsLists.loadActiveAuctionsList, []);\n\n React.useEffect(() => {\n _logger.debug('.useLoadActiveAuctionsList>>useEffect: setup');\n\n if (loadOnFirstRender) {\n loadAuctionsList(browserParams);\n }\n\n return () => {\n _logger.debug('.useLoadActiveAuctionsList>>useEffect: cleanup');\n }\n }, [loadOnFirstRender]);\n\n return [auctionsList, loadAuctionsList];\n}\n\n\n\nexport function useLoadCompletedAuctionsList(browserParams: ListingBrowserParams, loadOnFirstRender:boolean = false):[AuctionsModelListSubState, ()=>void] {\n const auctionsList = useSelector((state: RootState) => state.auctionsLists.completed);\n const dispatch = useDispatch();\n\n const loadAuctionsList = React.useCallback(dispatch.auctionsLists.loadCompletedAuctionsList, []);\n\n React.useEffect(() => {\n _logger.debug('.useLoadCompletedAuctionsList>>useEffect: setup');\n\n if (loadOnFirstRender) {\n loadAuctionsList(browserParams);\n }\n\n return () => {\n _logger.debug('.useLoadCompletedAuctionsList>>useEffect: cleanup');\n }\n }, [loadOnFirstRender]);\n\n return [auctionsList, loadAuctionsList];\n}\n\n\n\n\n\nexport function useRealtimeUpdatingAuctionsList(browserParams: ListingBrowserParams):AuctionsModelState {\n\n const {pageNumber, pageSize} = browserParams;\n\n const auctionsLists = useSelector((state: RootState) => state.auctionsLists);\n const dispatch = useDispatch();\n\n React.useEffect(() => {\n dispatch.auctionsLists.loadActiveAuctionsList(browserParams);\n dispatch.auctionsLists.loadCompletedAuctionsList(browserParams);\n }, [pageNumber, pageSize]);\n\n React.useEffect(() => {\n _logger.debug('.useRealtimeUpdatingAuctionsList>useEffect: setup');\n\n\n // TODO: register for remote events:\n // - webcast status changes\n\n const cleanupHandlerForBiddingWarrantChanges = AppController.instance.remoteEventsEmitter\n .onAuctionBiddingWarrantStateChange((change) => {\n _logger.debug('.useEffect>onAuctionBiddingWarrantStateChange: ', change);\n dispatch.auctionsLists.reloadAuction({ auctionId: change.auctionId });\n });\n\n const cleanupHandlerForAuctionVisibility = AppController.instance.remoteEventsEmitter\n .onAuctionVisibilityChange(async (change) => {\n _logger.debug('.useEffect>onAuctionVisibilityChange: ', change);\n if (change.isVisible) {\n dispatch.auctionsLists.reloadAuction({ auctionId: change.auctionId });\n }\n else {\n dispatch.auctionsLists.removeAuction({ auctionId: change.auctionId });\n }\n });\n\n const cleanupHandlerForAuctionDescriptiveUpdate = AppController.instance.remoteEventsEmitter\n .onAuctionDescriptiveChange(async (update) => {\n _logger.debug('.useEffect>onDescriptiveUpdate: ', update.auctionId);\n dispatch.auctionsLists.reloadAuction({ auctionId: update.auctionId });\n });\n\n\n return () => {\n _logger.debug('.useEffect: cleanup');\n cleanupHandlerForBiddingWarrantChanges();\n cleanupHandlerForAuctionVisibility();\n cleanupHandlerForAuctionDescriptiveUpdate();\n }\n\n }, []);\n\n\n return auctionsLists;\n}\n\n", "import React from \"react\";\nimport {useDispatch, useSelector} from \"react-redux\";\nimport {DateTime} from \"luxon\";\nimport {Dispatch, RootState} from \"../rematch/store\";\nimport {ApiResourceDetailsLevelsEnum, AuctionTimelineStateCodeID_Enum, BiddingWarrantStateCode_Enum} from \"../type_defs/api\";\nimport {TaggedLogger} from \"../utilities\";\nimport AppController from \"../AppController\";\nimport {Auction_ModelTypeDef} from \"../type_defs/model\";\nimport {CurrentAuctionModelState} from \"../rematch/models/currentAuctionModel\";\nimport StaticModelsAndConstants from \"../StaticModelsAndConstants\";\n\n// const _logger = TaggedLogger.get('CurrentAuctionHook')\n\n\nexport function useCurrentAuction():Auction_ModelTypeDef {\n return useSelector((state: RootState) => state.currentAuction.auction);\n}\n\nexport function useCurrentAuctionModelState():CurrentAuctionModelState {\n return useSelector((state: RootState) => state.currentAuction);\n}\n\n\n\nconst _logger_hookLoadAuction = TaggedLogger.get('useLoadAuctionAsCurrentAndRegisterForRealTimeUpdates')\n\nexport function useLoadAuctionAsCurrentAndRegisterForRealTimeUpdates(auctionId:number):void {\n\n const dispatch = useDispatch();\n\n React.useEffect(() => {\n if (auctionId) {\n dispatch.currentAuction.asyncFetchLoad({ auctionId, detailsLevel: ApiResourceDetailsLevelsEnum.minimal });\n }\n }, [auctionId]);\n\n\n const storeCurrentAuctionId = useSelector((state: RootState) => state.currentAuction.auctionId);\n\n React.useEffect(() => {\n _logger_hookLoadAuction.debug('.useEffect: setup: storeCurrentAuctionId: ', storeCurrentAuctionId);\n\n if (! storeCurrentAuctionId) {\n // first render, before load\n return;\n }\n\n const cleanupHandlerForAuctionVisibilityChange = AppController.instance.remoteEventsEmitter\n .onAuctionVisibilityChange(async (data) => {\n _logger_hookLoadAuction.debug('.useEffect>onAuctionVisibilityChange: ', data);\n\n if (data.auctionId !== auctionId) {\n // ignore for any other auction except *this* current in-view one\n return;\n }\n\n if (! data.isVisible) {\n // this means the current in-view auction was unpublished (it was set to draft|archive)\n dispatch.currentAuction.setFetchError('Auctioneer has removed the Auction.');\n }\n });\n\n\n const cleanupHandlerForAuctionDescriptiveUpdate = AppController.instance.remoteEventsEmitter\n .onAuctionDescriptiveChange(async (data) => {\n _logger_hookLoadAuction.debug('.useEffect>onAuctionDescriptiveChange: ', data);\n\n if (data.auctionId !== auctionId) {\n // ignore for any other auction except *this* current in-view one\n return;\n }\n\n dispatch.currentAuction.asyncFetchLoad({ auctionId, detailsLevel: ApiResourceDetailsLevelsEnum.full });\n });\n\n\n const cleanupHandlerForAuctionBiddingWarrantChange = AppController.instance.remoteEventsEmitter\n .onAuctionBiddingWarrantStateChange(async (data) => {\n _logger_hookLoadAuction.debug('.useEffect>onAuctionBiddingWarrantStateChange: ', data);\n\n if (data.auctionId !== auctionId) {\n // ignore for any other auction except *this* current in-view one\n return;\n }\n\n dispatch.currentAuction.updateMyBiddingWarrantStateByCode(data.state as BiddingWarrantStateCode_Enum);\n dispatch.currentAuction.asyncFetchLoad({ auctionId, detailsLevel: ApiResourceDetailsLevelsEnum.metal });\n });\n\n\n const intervalReload = setInterval(() => {\n\n dispatch.currentAuction.asyncFetchLoad({ auctionId, detailsLevel: ApiResourceDetailsLevelsEnum.metal });\n\n }, 5 * 60_000); // every 5 minutes\n\n\n return () => {\n _logger_hookLoadAuction.debug('.useEffect: cleanup');\n\n clearInterval(intervalReload);\n cleanupHandlerForAuctionVisibilityChange();\n cleanupHandlerForAuctionDescriptiveUpdate();\n cleanupHandlerForAuctionBiddingWarrantChange();\n }\n\n }, [storeCurrentAuctionId]);\n}\n\n\nfunction useCurrentAuctionWithRealtimeUpdatedStatus():Auction_ModelTypeDef|null {\n const auction = useCurrentAuction() || {} as Auction_ModelTypeDef;\n const auctionId = auction.id;\n const { auctionType,\n startsAt, closingStartsAt, webcastStartsAt, closingEndsAt, completesAt, isCompleted,\n\n timelineState, currentSegmentType, webcastIsPrepared\n } = auction;\n\n let newTimelineState = timelineState;\n let newCurrentSegment = currentSegmentType;\n\n if (auctionId) {\n const timeNow = DateTime.now();\n\n if (isCompleted) {\n newTimelineState = StaticModelsAndConstants.AuctionTimelineStates.getById(AuctionTimelineStateCodeID_Enum.completed);\n }\n\n }\n\n\n return React.useMemo(() => {\n if (!auctionId) {\n return null;\n }\n\n return {\n ... auction,\n }\n },\n [\n auctionId,\n auctionType,\n startsAt?.toUnixInteger(),\n closingStartsAt?.toUnixInteger(),\n webcastStartsAt?.toUnixInteger(),\n closingEndsAt?.toUnixInteger(),\n completesAt?.toUnixInteger(),\n ]);\n}\n", "import {CurrentBidder} from \"../type_defs/model\";\nimport AppController from \"../AppController\";\n\n\nexport default function getCurrentBidder(args:{ onNotAuthenticated?:()=>void } = {}):CurrentBidder|null {\n\n const currentBidder = AppController.instance?.currentBidder;\n\n const {onNotAuthenticated} = args;\n\n if (!currentBidder?.id && onNotAuthenticated) {\n onNotAuthenticated();\n }\n\n return currentBidder;\n}\n", "import React from \"react\";\nimport {useDispatch, useSelector} from \"react-redux\";\nimport {Dispatch, RootState} from \"../rematch/store\";\nimport {CurrentAuctionLotsModelState} from \"../rematch/models/currentAuctionLotsModel\";\nimport {ListingBrowserParams, RunningCatalogLot_ModelTypeDef} from \"../type_defs/model\";\nimport AppController from \"../AppController\";\nimport {TaggedLogger} from \"../utilities\";\nimport getCurrentBidder from \"./getCurrentBidder\";\n\nconst _logger = TaggedLogger.get('CurrentAuctionLotsListHook');\n\n\n\nexport function useCurrentAuctionSingleLot(lotId:number):RunningCatalogLot_ModelTypeDef {\n\n const dispatch = useDispatch();\n\n React.useEffect(() => {\n dispatch.currentAuctionLots.asyncLoadForSingleLotView({ lotId });\n }, [lotId])\n\n return useSelector((state: RootState) => state.currentAuctionLots.lotInFocus);\n}\n\n\n\n\n\ntype useCurrentAuctionLotsListBrowsable_HookReturnTypeDef = CurrentAuctionLotsModelState & {\n validSafePageNumber:(number)=>number\n}\n\nexport function useCurrentAuctionLotsListBrowsable(auctionId: number, lotIdInFocus: number|null, browseParams:ListingBrowserParams):useCurrentAuctionLotsListBrowsable_HookReturnTypeDef {\n\n const { pageNumber, pageSize, filters, sortingCriteria, entityDetailsLevel } = browseParams;\n\n const dispatch = useDispatch();\n\n React.useEffect(() => {\n dispatch.currentAuctionLots.resetDataBeforeInitialFetch();\n }, [auctionId]);\n\n\n React.useEffect(() => {\n //HACK! do not dispatch async reload if a lot is in focus\n if (! lotIdInFocus) {\n dispatch.currentAuctionLots.asyncLoadForBrowsableView({pageNumber, pageSize, filters, sortingCriteria, entityDetailsLevel});\n }\n }, [auctionId, lotIdInFocus, pageNumber, pageSize, filters, sortingCriteria, entityDetailsLevel])\n\n\n const lotsModel = useSelector((state: RootState) => state.currentAuctionLots);\n const pagesCount = lotsModel?.pagesCount || 1;\n\n const validSafePageNumber = React.useCallback((reqPageNumber:number) => {\n // ensure reqPageNumber is between 1 and pagesCount\n return Math.min(pagesCount, Math.max(1, reqPageNumber));\n }, [auctionId, pagesCount]);\n\n\n\n return {\n ... lotsModel,\n validSafePageNumber,\n };\n}\n\n\n\n\n\n\nexport function useRemoteUpdatingAuctionLotsChangeListener(auctionId:number) {\n const dispatch = useDispatch();\n\n React.useEffect(() => {\n\n const unbindChannelAuctionLots = AppController.instance.remoteEventsEmitter.onAuctionLotsChange(auctionId, (data) => {\n _logger.debug('[useRemoteUpdatingAuctionLotsChangeListener]>>useEffect>onAuctionLotsChange: data:', data);\n const {lotId} = data;\n dispatch.currentAuctionLots.asyncFetchAndUpdateRunningLotWithSideEffects({ auctionId, lotId });\n });\n\n return () => {\n unbindChannelAuctionLots();\n }\n }, [auctionId]);\n}\n\n\n\n\nexport function useRemoteUpdatingLotsInterestChangeListener(auctionId:number) {\n const dispatch = useDispatch();\n const currentBidderId = getCurrentBidder()?.id;\n\n React.useEffect(() => {\n\n const unbindListener = AppController.instance.remoteEventsEmitter.onMyLotsInterestChange((data) => {\n _logger.debug('[useRemoteUpdatingLotsInterestChangeListener]>>useEffect>onMyLotsInterestChange: data:', data);\n const {lotId, auctionId:dataAuctionId} = data;\n if (dataAuctionId === auctionId) {\n dispatch.currentAuctionLots.asyncFetchAndUpdateLotChangedInterest({lotId});\n }\n });\n\n return () => {\n unbindListener();\n }\n }, [currentBidderId, auctionId]);\n}\n", "import {\n useLoadActiveAuctionsList,\n useLoadCompletedAuctionsList,\n useRealtimeUpdatingAuctionsList\n} from \"./AuctionsListHook\";\n\n\nimport {\n useCurrentAuction,\n useCurrentAuctionModelState,\n useLoadAuctionAsCurrentAndRegisterForRealTimeUpdates\n} from \"./CurrentAuctionHooks\";\n\n\nimport {\n useCurrentAuctionLotsListBrowsable,\n useCurrentAuctionSingleLot,\n useRemoteUpdatingAuctionLotsChangeListener,\n useRemoteUpdatingLotsInterestChangeListener\n} from \"./CurrentAuctionLotsListHook\";\n\nimport {useDispatch} from \"react-redux\";\nimport {Dispatch} from \"../rematch/store\";\n\n\nconst useAppDispatch = useDispatch;\n\nexport {\n useAppDispatch,\n\n useLoadActiveAuctionsList,\n useLoadCompletedAuctionsList,\n useRealtimeUpdatingAuctionsList,\n\n useCurrentAuction,\n useCurrentAuctionModelState,\n useLoadAuctionAsCurrentAndRegisterForRealTimeUpdates,\n\n useCurrentAuctionLotsListBrowsable,\n useRemoteUpdatingAuctionLotsChangeListener,\n useRemoteUpdatingLotsInterestChangeListener,\n\n useCurrentAuctionSingleLot,\n};\n", "import * as Redux from 'redux'\nimport {\n\tAction,\n\tConfigRedux,\n\tModelReducers,\n\tNamedModel,\n\tRematchBag,\n\tDevtoolOptions,\n\tModels,\n\tRematchRootState,\n} from './types'\n\n/**\n * Creates 'combined' reducer for each model and then merges those reducers\n * together into a 'root' reducer. It then creates a Redux store with\n * middlewares and enhancers.\n */\nexport default function createReduxStore<\n\tTModels extends Models,\n\tTExtraModels extends Models,\n\tRootState = RematchRootState\n>(bag: RematchBag): Redux.Store {\n\tbag.models.forEach((model) => createModelReducer(bag, model))\n\n\tconst rootReducer = createRootReducer(bag)\n\n\tconst middlewares = Redux.applyMiddleware(...bag.reduxConfig.middlewares)\n\tconst enhancers = bag.reduxConfig.devtoolComposer\n\t\t? bag.reduxConfig.devtoolComposer(...bag.reduxConfig.enhancers, middlewares)\n\t\t: composeEnhancersWithDevtools(bag.reduxConfig.devtoolOptions)(\n\t\t\t\t...bag.reduxConfig.enhancers,\n\t\t\t\tmiddlewares\n\t\t )\n\n\tconst createStore = bag.reduxConfig.createStore || Redux.createStore\n\tconst bagInitialState = bag.reduxConfig.initialState\n\tconst initialState = bagInitialState === undefined ? {} : bagInitialState\n\n\treturn createStore(\n\t\trootReducer,\n\t\tinitialState,\n\t\tenhancers\n\t)\n}\n\n/**\n * Creates a combined reducer for a given model. What it means is that:\n * - it forms an action name for each model's reducer as 'modelName/reducerKey'\n * - it creates a mapping from action name to its reducer\n * - it wraps the mapping with a function (combined reducer) that selects and\n * runs a reducer based on the incoming action\n * - if the model also has a base reducer defined, it creates a function which\n * first runs the incoming action through this reducer and then passes the\n * resulting state and the same action to combined reducer\n *\n * The final result - a function, is returned.\n */\nexport function createModelReducer<\n\tTModels extends Models,\n\tTExtraModels extends Models,\n\tTState extends NamedModel['state'] = any\n>(bag: RematchBag, model: NamedModel): void {\n\tconst modelReducers: ModelReducers = {}\n\n\t// build action name for each reducer and create mapping from name to reducer\n\tconst modelReducerKeys = Object.keys(model.reducers)\n\tmodelReducerKeys.forEach((reducerKey) => {\n\t\tconst actionName = isAlreadyActionName(reducerKey)\n\t\t\t? reducerKey\n\t\t\t: `${model.name}/${reducerKey}`\n\n\t\tmodelReducers[actionName] = model.reducers[reducerKey]\n\t})\n\n\t// select and run a reducer based on the incoming action\n\tconst combinedReducer = (\n\t\tstate: TState = model.state,\n\t\taction: Action\n\t): TState => {\n\t\tif (action.type in modelReducers) {\n\t\t\treturn modelReducers[action.type](\n\t\t\t\tstate,\n\t\t\t\taction.payload,\n\t\t\t\taction.meta\n\t\t\t\t// we use augmentation because a reducer can return void due immer plugin,\n\t\t\t\t// which makes optional returning the reducer state\n\t\t\t) as TState\n\t\t}\n\n\t\treturn state\n\t}\n\n\tconst modelBaseReducer = model.baseReducer\n\n\t// when baseReducer is defined, run the action first through it\n\tlet reducer = !modelBaseReducer\n\t\t? combinedReducer\n\t\t: (state: TState = model.state, action: Action): TState =>\n\t\t\t\tcombinedReducer(modelBaseReducer(state, action), action)\n\n\tbag.forEachPlugin('onReducer', (onReducer) => {\n\t\treducer = onReducer(reducer, model.name, bag) || reducer\n\t})\n\n\tbag.reduxConfig.reducers[model.name] = reducer\n}\n\n/**\n * It merges all reducers in config using mergeReducers function. Additionally,\n * if user supplied any rootReducers, a wrapper function around merged reducers\n * is created. It first feeds each into its corresponding 'root' reducer (if\n * it's available), and then passes on the resulting state to the merged reducer.\n */\nexport function createRootReducer<\n\tTRootState,\n\tTModels extends Models,\n\tTExtraModels extends Models\n>(bag: RematchBag): Redux.Reducer {\n\tconst { rootReducers } = bag.reduxConfig\n\tconst mergedReducers = mergeReducers(bag.reduxConfig)\n\tlet rootReducer = mergedReducers\n\n\tif (rootReducers && Object.keys(rootReducers).length) {\n\t\trootReducer = (\n\t\t\tstate: TRootState | undefined,\n\t\t\taction: Action\n\t\t): TRootState => {\n\t\t\tconst actionRootReducer = rootReducers[action.type]\n\n\t\t\tif (actionRootReducer) {\n\t\t\t\treturn mergedReducers(actionRootReducer(state, action), action)\n\t\t\t}\n\n\t\t\treturn mergedReducers(state, action)\n\t\t}\n\t}\n\n\tbag.forEachPlugin('onRootReducer', (onRootReducer) => {\n\t\trootReducer = onRootReducer(rootReducer, bag) || rootReducer\n\t})\n\n\treturn rootReducer\n}\n\n/**\n * Merges all reducers defined in config into one function using user supplied\n * or default combineReducers function.\n * If there are no reducers defined, it returns a function that just returns\n * the state for all incoming actions.\n */\nfunction mergeReducers(\n\treduxConfig: ConfigRedux\n): Redux.Reducer {\n\tconst combineReducers = reduxConfig.combineReducers || Redux.combineReducers\n\n\tif (!Object.keys(reduxConfig.reducers).length) {\n\t\treturn (state: any): TRootState => state\n\t}\n\n\treturn combineReducers(reduxConfig.reducers as Redux.ReducersMapObject)\n}\n\n/**\n * Returns Redux Devtools compose method unless it's disabled, in which case it\n * returns default Redux.compose.\n */\nfunction composeEnhancersWithDevtools(\n\tdevtoolOptions: DevtoolOptions = {}\n): (...args: any[]) => Redux.StoreEnhancer {\n\treturn !devtoolOptions.disabled &&\n\t\ttypeof window === 'object' &&\n\t\twindow.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__\n\t\t? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__(devtoolOptions)\n\t\t: Redux.compose\n}\n\n/**\n * Determines if a reducer key is already an action name, for example -\n * a listener on another model.\n */\nfunction isAlreadyActionName(reducerKey: string): boolean {\n\treturn reducerKey.indexOf('/') > -1\n}\n", "import {\n\tConfig,\n\tModelEffects,\n\tModelReducers,\n\tNamedModel,\n\tPlugin,\n\tModels,\n} from './types'\n\n/**\n * If the first item is true, it means there is an error described by\n * the second item.\n */\nexport type Validation = [boolean | undefined, string]\n\n/**\n * Checks if a parameter is a valid object.\n */\nexport const isObject = (obj: T): boolean =>\n\ttypeof obj === 'object' && obj !== null && !Array.isArray(obj)\n\n/**\n * Checks if a parameter is a valid function but only when it's defined.\n * Otherwise, always returns true.\n */\nexport const ifDefinedIsFunction = (func: T): boolean =>\n\t!func || typeof func === 'function'\n\n/**\n * Takes an array of arrays of validations. Collects all errors and throws.\n * Should be used by plugins to keep the validation behaviour the same for all\n * Rematch-related libraries.\n */\nconst validate = (runValidations: () => Validation[]): void => {\n\tif (process.env.NODE_ENV !== 'production') {\n\t\tconst validations = runValidations()\n\t\tconst errors: string[] = []\n\n\t\tvalidations.forEach((validation) => {\n\t\t\tconst isInvalid = validation[0]\n\t\t\tconst errorMessage = validation[1]\n\t\t\tif (isInvalid) {\n\t\t\t\terrors.push(errorMessage)\n\t\t\t}\n\t\t})\n\n\t\tif (errors.length > 0) {\n\t\t\tthrow new Error(errors.join(', '))\n\t\t}\n\t}\n}\n\nexport const validateConfig = <\n\tTModels extends Models,\n\tTExtraModels extends Models\n>(\n\tconfig: Config\n): void => {\n\tvalidate(() => [\n\t\t[!Array.isArray(config.plugins), 'init config.plugins must be an array'],\n\t\t[!isObject(config.models), 'init config.models must be an object'],\n\t\t[\n\t\t\t!isObject(config.redux.reducers),\n\t\t\t'init config.redux.reducers must be an object',\n\t\t],\n\t\t[\n\t\t\t!Array.isArray(config.redux.middlewares),\n\t\t\t'init config.redux.middlewares must be an array',\n\t\t],\n\t\t[\n\t\t\t!Array.isArray(config.redux.enhancers),\n\t\t\t'init config.redux.enhancers must be an array of functions',\n\t\t],\n\t\t[\n\t\t\t!ifDefinedIsFunction(config.redux.combineReducers),\n\t\t\t'init config.redux.combineReducers must be a function',\n\t\t],\n\t\t[\n\t\t\t!ifDefinedIsFunction(config.redux.createStore),\n\t\t\t'init config.redux.createStore must be a function',\n\t\t],\n\t])\n}\n\nexport const validateModel = >(\n\tmodel: NamedModel\n): void => {\n\tvalidate(() => [\n\t\t[!model, 'model config is required'],\n\t\t[typeof model.name !== 'string', 'model \"name\" [string] is required'],\n\t\t[\n\t\t\tmodel.state === undefined && model.baseReducer === undefined,\n\t\t\t'model \"state\" is required',\n\t\t],\n\t\t[\n\t\t\t!ifDefinedIsFunction(model.baseReducer),\n\t\t\t'model \"baseReducer\" must be a function',\n\t\t],\n\t])\n}\n\nexport const validatePlugin = <\n\tTModels extends Models,\n\tTExtraModels extends Models\n>(\n\tplugin: Plugin\n): void => {\n\tvalidate(() => [\n\t\t[\n\t\t\t!ifDefinedIsFunction(plugin.onStoreCreated),\n\t\t\t'Plugin onStoreCreated must be a function',\n\t\t],\n\t\t[!ifDefinedIsFunction(plugin.onModel), 'Plugin onModel must be a function'],\n\t\t[\n\t\t\t!ifDefinedIsFunction(plugin.onReducer),\n\t\t\t'Plugin onReducer must be a function',\n\t\t],\n\t\t[\n\t\t\t!ifDefinedIsFunction(plugin.onRootReducer),\n\t\t\t'Plugin onRootReducer must be a function',\n\t\t],\n\t\t[\n\t\t\t!ifDefinedIsFunction(plugin.createMiddleware),\n\t\t\t'Plugin createMiddleware must be a function',\n\t\t],\n\t])\n}\n\nexport const validateModelReducer = (\n\tmodelName: string,\n\treducers: ModelReducers,\n\treducerName: string\n): void => {\n\tvalidate(() => [\n\t\t[\n\t\t\t!!reducerName.match(/\\/.+\\//),\n\t\t\t`Invalid reducer name (${modelName}/${reducerName})`,\n\t\t],\n\t\t[\n\t\t\ttypeof reducers[reducerName] !== 'function',\n\t\t\t`Invalid reducer (${modelName}/${reducerName}). Must be a function`,\n\t\t],\n\t])\n}\n\nexport const validateModelEffect = >(\n\tmodelName: string,\n\teffects: ModelEffects,\n\teffectName: string\n): void => {\n\tvalidate(() => [\n\t\t[\n\t\t\t!!effectName.match(/\\//),\n\t\t\t`Invalid effect name (${modelName}/${effectName})`,\n\t\t],\n\t\t[\n\t\t\ttypeof effects[effectName] !== 'function',\n\t\t\t`Invalid effect (${modelName}/${effectName}). Must be a function`,\n\t\t],\n\t])\n}\n\nexport default validate\n", "import {\n\tAction,\n\tModelEffects,\n\tModelEffectsCreator,\n\tModels,\n\tNamedModel,\n\tRematchBag,\n\tRematchDispatcher,\n\tRematchStore,\n} from './types'\nimport { validateModelEffect, validateModelReducer } from './validate'\n\n/**\n * Builds a dispatcher for given model name and action name. The dispatched\n * action will have a type `modelName/actionName`.\n * Additionally, adds the isEffect property to the created dispatcher.\n * isEffect helps to differentiate effects dispatchers from reducer dispatchers.\n */\nconst createActionDispatcher = <\n\tTModels extends Models,\n\tTExtraModels extends Models\n>(\n\trematch: RematchStore,\n\tmodelName: string,\n\tactionName: string,\n\tisEffect: boolean\n): RematchDispatcher => {\n\treturn Object.assign(\n\t\t(payload?: any, meta?: any): Action => {\n\t\t\tconst action: Action = { type: `${modelName}/${actionName}` }\n\n\t\t\tif (typeof payload !== 'undefined') {\n\t\t\t\taction.payload = payload\n\t\t\t}\n\n\t\t\tif (typeof meta !== 'undefined') {\n\t\t\t\taction.meta = meta\n\t\t\t}\n\n\t\t\treturn rematch.dispatch(action)\n\t\t},\n\t\t{\n\t\t\tisEffect,\n\t\t}\n\t)\n}\n\n/**\n * Creates a dispatcher object for a model - it contains a mapping from all\n * reducers to functions which dispatch their corresponding actions.\n */\nexport const createReducerDispatcher = <\n\tTModels extends Models,\n\tTExtraModels extends Models,\n\tTModel extends NamedModel\n>(\n\trematch: RematchStore,\n\tmodel: TModel\n): void => {\n\tconst modelDispatcher = rematch.dispatch[model.name]\n\n\t// map reducer names to dispatch actions\n\tconst modelReducersKeys = Object.keys(model.reducers)\n\tmodelReducersKeys.forEach((reducerName) => {\n\t\tvalidateModelReducer(model.name, model.reducers, reducerName)\n\n\t\tmodelDispatcher[reducerName] = createActionDispatcher(\n\t\t\trematch,\n\t\t\tmodel.name,\n\t\t\treducerName,\n\t\t\tfalse\n\t\t)\n\t})\n}\n\n/**\n * Creates effects dispatcher for a model - it contains a mapping from all\n * effects *names* to functions which dispatch their corresponding actions.\n */\nexport const createEffectDispatcher = <\n\tTModels extends Models,\n\tTExtraModels extends Models,\n\tTModel extends NamedModel\n>(\n\trematch: RematchStore,\n\tbag: RematchBag,\n\tmodel: TModel\n): void => {\n\tconst modelDispatcher = rematch.dispatch[model.name]\n\tlet effects: ModelEffects = {}\n\n\t// 'effects' might be actually a function creating effects\n\tif (model.effects) {\n\t\teffects =\n\t\t\ttypeof model.effects === 'function'\n\t\t\t\t? (model.effects as ModelEffectsCreator)(rematch.dispatch)\n\t\t\t\t: model.effects\n\t}\n\n\t// map effects names to dispatch actions\n\tconst effectKeys = Object.keys(effects)\n\teffectKeys.forEach((effectName) => {\n\t\tvalidateModelEffect(model.name, effects, effectName)\n\n\t\tbag.effects[`${model.name}/${effectName}`] =\n\t\t\teffects[effectName].bind(modelDispatcher)\n\n\t\tmodelDispatcher[effectName] = createActionDispatcher(\n\t\t\trematch,\n\t\t\tmodel.name,\n\t\t\teffectName,\n\t\t\ttrue\n\t\t)\n\t})\n}\n", "import { Config, Model, Models, NamedModel, RematchBag } from './types'\nimport { validateModel } from './validate'\n\n/**\n * Creates and returns a 'Rematch Bag', which is a set of configuration options\n * used by the Rematch library in various functions.\n */\nexport default function createRematchBag<\n\tTModels extends Models,\n\tTExtraModels extends Models\n>(config: Config): RematchBag {\n\treturn {\n\t\tmodels: createNamedModels(config.models),\n\t\treduxConfig: config.redux,\n\t\tforEachPlugin(method, fn): void {\n\t\t\tconfig.plugins.forEach((plugin) => {\n\t\t\t\tif (plugin[method]) {\n\t\t\t\t\tfn(plugin[method]!)\n\t\t\t\t}\n\t\t\t})\n\t\t},\n\t\teffects: {},\n\t}\n}\n\n/**\n * Transforms mapping from a model name to a model object, into an array of\n * 'named' models - models with embedded name and default value for reducers\n * if user didn't provide any.\n */\nfunction createNamedModels>(\n\tmodels: TModels | Partial\n): NamedModel[] {\n\treturn Object.keys(models).map((modelName: string) => {\n\t\tconst model = createNamedModel(modelName, (models as TModels)[modelName])\n\t\tvalidateModel(model)\n\t\treturn model\n\t})\n}\n\n/**\n * Transforms a model into 'named' model - model which contains 'name' and\n * 'reducers' properties if user didn't provide any.\n */\nfunction createNamedModel>(\n\tname: string,\n\tmodel: Model\n): NamedModel {\n\treturn {\n\t\tname,\n\t\treducers: {},\n\t\t...model,\n\t}\n}\n", "import { Middleware } from 'redux'\nimport {\n\tAction,\n\tConfig,\n\tExposedFunction,\n\tModels,\n\tNamedModel,\n\tObjectNotAFunction,\n\tPlugin,\n\tRematchBag,\n\tRematchStore,\n\tModelDispatcher,\n\tRematchDispatch,\n} from './types'\nimport createReduxStore, {\n\tcreateModelReducer,\n\tcreateRootReducer,\n} from './reduxStore'\nimport { createReducerDispatcher, createEffectDispatcher } from './dispatcher'\nimport { validateModel } from './validate'\nimport createRematchBag from './bag'\n\nexport default function createRematchStore<\n\tTModels extends Models,\n\tTExtraModels extends Models\n>(config: Config): RematchStore {\n\t// setup rematch 'bag' for storing useful values and functions\n\tconst bag = createRematchBag(config)\n\n\t// add middleware for handling effects\n\tbag.reduxConfig.middlewares.push(createEffectsMiddleware(bag))\n\n\t// collect middlewares from plugins\n\tbag.forEachPlugin('createMiddleware', (createMiddleware) => {\n\t\tbag.reduxConfig.middlewares.push(createMiddleware(bag))\n\t})\n\n\tconst reduxStore = createReduxStore(bag)\n\n\tlet rematchStore = {\n\t\t...reduxStore,\n\t\tname: config.name,\n\t\taddModel(model: NamedModel) {\n\t\t\tvalidateModel(model)\n\t\t\tcreateModelReducer(bag, model)\n\t\t\tprepareModel(rematchStore, model)\n\t\t\tenhanceModel(rematchStore, bag, model)\n\t\t\treduxStore.replaceReducer(createRootReducer(bag))\n\t\t\treduxStore.dispatch({ type: '@@redux/REPLACE' })\n\t\t},\n\t} as RematchStore\n\n\taddExposed(rematchStore, config.plugins)\n\n\t/**\n\t * generate dispatch[modelName][actionName] for all reducers and effects\n\t *\n\t * Note: To have circular models accessible in effects method with destructing,\n\t * ensure that model generation and effects generation execute in\n\t * different steps.\n\t */\n\tbag.models.forEach((model) => prepareModel(rematchStore, model))\n\tbag.models.forEach((model) => enhanceModel(rematchStore, bag, model))\n\n\tbag.forEachPlugin('onStoreCreated', (onStoreCreated) => {\n\t\trematchStore = onStoreCreated(rematchStore, bag) || rematchStore\n\t})\n\n\treturn rematchStore\n}\n\nfunction createEffectsMiddleware<\n\tTModels extends Models,\n\tTExtraModels extends Models\n>(bag: RematchBag): Middleware {\n\treturn (store) =>\n\t\t(next) =>\n\t\t(action: Action): any => {\n\t\t\tif (action.type in bag.effects) {\n\t\t\t\t// first run reducer action if exists\n\t\t\t\tnext(action)\n\n\t\t\t\t// then run the effect and return its result\n\t\t\t\treturn (bag.effects as any)[action.type](\n\t\t\t\t\taction.payload,\n\t\t\t\t\tstore.getState(),\n\t\t\t\t\taction.meta\n\t\t\t\t)\n\t\t\t}\n\n\t\t\treturn next(action)\n\t\t}\n}\n\nfunction prepareModel<\n\tTModels extends Models,\n\tTExtraModels extends Models,\n\tTModel extends NamedModel\n>(rematchStore: RematchStore, model: TModel): void {\n\tconst modelDispatcher = {} as ModelDispatcher\n\n\t// inject model so effects creator can access it\n\trematchStore.dispatch[`${model.name}` as keyof RematchDispatch] =\n\t\tmodelDispatcher\n\n\tcreateReducerDispatcher(rematchStore, model)\n}\n\nfunction enhanceModel<\n\tTModels extends Models,\n\tTExtraModels extends Models,\n\tTModel extends NamedModel\n>(\n\trematchStore: RematchStore,\n\tbag: RematchBag,\n\tmodel: TModel\n): void {\n\tcreateEffectDispatcher(rematchStore, bag, model)\n\n\tbag.forEachPlugin('onModel', (onModel) => {\n\t\tonModel(model, rematchStore)\n\t})\n}\n\n/**\n * Adds properties exposed by plugins into the Rematch instance. If a exposed\n * property is a function, it passes rematch as the first argument.\n *\n * If you're implementing a plugin in TypeScript, extend Rematch namespace by\n * adding the properties that you exposed from your plugin.\n */\nfunction addExposed<\n\tTModels extends Models,\n\tTExtraModels extends Models\n>(\n\tstore: RematchStore,\n\tplugins: Plugin[]\n): void {\n\tplugins.forEach((plugin) => {\n\t\tif (!plugin.exposed) return\n\t\tconst pluginKeys = Object.keys(plugin.exposed)\n\t\tpluginKeys.forEach((key) => {\n\t\t\tif (!plugin.exposed) return\n\t\t\tconst exposedItem = plugin.exposed[key] as\n\t\t\t\t| ExposedFunction\n\t\t\t\t| ObjectNotAFunction\n\t\t\tconst isExposedFunction = typeof exposedItem === 'function'\n\n\t\t\tstore[key] = isExposedFunction\n\t\t\t\t? (...params: any[]): any =>\n\t\t\t\t\t\t(exposedItem as ExposedFunction)(\n\t\t\t\t\t\t\tstore,\n\t\t\t\t\t\t\t...params\n\t\t\t\t\t\t)\n\t\t\t\t: Object.create(plugin.exposed[key])\n\t\t})\n\t})\n}\n", "import { InitConfig, Config, Models } from './types'\nimport { validateConfig, validatePlugin } from './validate'\n\nlet count = 0\n\n/**\n * Builds complete Rematch config using default values for properties not\n * supplied by the user. Additionally, applies changes to the config made by\n * the plugins selected by the user.\n */\nexport default function createConfig<\n\tTModels extends Models,\n\tTExtraModels extends Models\n>(\n\tinitConfig: InitConfig\n): Config {\n\tconst storeName = initConfig.name ?? `Rematch Store ${count}`\n\n\tcount += 1\n\n\tconst config = {\n\t\tname: storeName,\n\t\tmodels: initConfig.models || {},\n\t\tplugins: initConfig.plugins || [],\n\t\tredux: {\n\t\t\treducers: {},\n\t\t\trootReducers: {},\n\t\t\tenhancers: [],\n\t\t\tmiddlewares: [],\n\t\t\t...initConfig.redux,\n\t\t\tdevtoolOptions: {\n\t\t\t\tname: storeName,\n\t\t\t\t...(initConfig.redux?.devtoolOptions ?? {}),\n\t\t\t},\n\t\t},\n\t} as Config\n\n\tvalidateConfig(config)\n\n\t// Apply changes to the config required by plugins\n\tconfig.plugins.forEach((plugin) => {\n\t\tif (plugin.config) {\n\t\t\t// Collect new models\n\t\t\tconfig.models = merge(config.models, plugin.config.models)\n\n\t\t\t// Collect redux configuration changes\n\t\t\tif (plugin.config.redux) {\n\t\t\t\tconfig.redux.initialState = merge(\n\t\t\t\t\tconfig.redux.initialState,\n\t\t\t\t\tplugin.config.redux.initialState\n\t\t\t\t)\n\n\t\t\t\tconfig.redux.reducers = merge(\n\t\t\t\t\tconfig.redux.reducers,\n\t\t\t\t\tplugin.config.redux.reducers\n\t\t\t\t)\n\n\t\t\t\tconfig.redux.rootReducers = merge(\n\t\t\t\t\tconfig.redux.rootReducers,\n\t\t\t\t\tplugin.config.redux.reducers\n\t\t\t\t)\n\n\t\t\t\tconfig.redux.enhancers = [\n\t\t\t\t\t...config.redux.enhancers,\n\t\t\t\t\t...(plugin.config.redux.enhancers || []),\n\t\t\t\t]\n\n\t\t\t\tconfig.redux.middlewares = [\n\t\t\t\t\t...config.redux.middlewares,\n\t\t\t\t\t...(plugin.config.redux.middlewares || []),\n\t\t\t\t]\n\n\t\t\t\tconfig.redux.combineReducers =\n\t\t\t\t\tconfig.redux.combineReducers || plugin.config.redux.combineReducers\n\n\t\t\t\tconfig.redux.createStore =\n\t\t\t\t\tconfig.redux.createStore || plugin.config.redux.createStore\n\t\t\t}\n\t\t}\n\n\t\tvalidatePlugin(plugin)\n\t})\n\n\treturn config as Config\n}\n\n/**\n * Shallow merges original object with the extra object, giving the precedence\n * to the original object.\n */\nfunction merge<\n\tT extends Record,\n\tU extends Record = T\n>(original: T, extra?: U): T | (T & U) {\n\treturn extra ? { ...extra, ...original } : original\n}\n", "import createRematchStore from './rematchStore'\nimport { InitConfig, Models, RematchStore, ModelCreator } from './types'\nimport createConfig from './config'\n\n/**\n * Prepares a complete configuration and creates a Rematch store.\n */\nexport const init = <\n\tTModels extends Models,\n\tTExtraModels extends Models = Record\n>(\n\tinitConfig?: InitConfig\n): RematchStore => {\n\tconst config = createConfig(initConfig || {})\n\treturn createRematchStore(config)\n}\n\nexport const createModel: ModelCreator = () => (mo) => mo as any\n\nexport default {\n\tinit,\n\tcreateModel,\n}\n\nexport * from './types'\n", "import { Plugin, Models } from '@rematch/core'\nimport produce from 'immer'\nimport Redux from 'redux'\n\nexport type ImmerPluginConfig = {\n\twhitelist?: string[]\n\tblacklist?: string[]\n}\n\nfunction wrapReducerWithImmer(reducer: Redux.Reducer) {\n\treturn (state: any, payload: any): any => {\n\t\tif (state === undefined) return reducer(state, payload)\n\t\treturn produce(state, (draft: any) => reducer(draft, payload))\n\t}\n}\n\nconst immerPlugin = <\n\tTModels extends Models,\n\tTExtraModels extends Models = Record\n>(\n\tconfig?: ImmerPluginConfig\n): Plugin => ({\n\tonReducer(reducer: Redux.Reducer, model: string): Redux.Reducer | void {\n\t\tif (\n\t\t\t!config ||\n\t\t\t(!config.whitelist && !config.blacklist) ||\n\t\t\t(config.whitelist && config.whitelist.includes(model)) ||\n\t\t\t(config.blacklist && !config.blacklist.includes(model))\n\t\t) {\n\t\t\treturn wrapReducerWithImmer(reducer)\n\t\t}\n\n\t\treturn undefined\n\t},\n})\n\nexport default immerPlugin\n", "import {createModel} from \"@rematch/core\";\nimport type {RootModel} from \"./index\";\nimport {Auction_ModelTypeDef, ListingBrowserParams, PaginatedList_TypeDef} from \"../../type_defs/model\";\nimport AppController from \"../../AppController\";\nimport {ApiResourceDetailsLevelsEnum} from \"../../type_defs/api\";\n\nexport type AuctionsModelListSubState = {\n pageSize: number;\n totalCount: number;\n pageNumber: number;\n pagesCount: number;\n isFetching?: boolean,\n fetchError?:string|boolean,\n list: Auction_ModelTypeDef[]\n}\n\nexport type AuctionsModelState = {\n active: AuctionsModelListSubState,\n completed: AuctionsModelListSubState,\n byId: Map,\n}\n\nexport const auctionsLists = createModel()({\n name: 'auctionsLists',\n\n state: {\n active: {\n isFetching: true,\n list: [],\n totalCount: 0,\n pageNumber: 1,\n pagesCount: 1,\n },\n completed: {\n isFetching: true,\n list: [],\n totalCount: 0,\n pageNumber: 1,\n pagesCount: 1,\n },\n byId: new Map(),\n } as AuctionsModelState,\n\n\n reducers: {\n setFetchedActiveList: (state, payload:PaginatedList_TypeDef) => {\n state.active.isFetching = false;\n state.active.fetchError = null;\n state.active.list = payload.list;\n payload.list.forEach((a) => {\n state.byId.set(a.id, a);\n });\n state.active.pageNumber = payload.pageNumber;\n state.active.pageSize = payload.pageSize;\n state.active.totalCount = payload.totalCount;\n state.active.pagesCount = payload.pagesCount;\n },\n\n setFetchErrorForActiveList: (state, payload:string) => {\n state.active.isFetching = false;\n state.active.fetchError = payload;\n },\n\n setFetchedCompletedList: (state, payload:PaginatedList_TypeDef) => {\n state.completed.isFetching = false;\n state.completed.fetchError = null;\n state.completed.list = payload.list;\n payload.list.forEach((a) => {\n state.byId.set(a.id, a);\n });\n state.completed.pageNumber = payload.pageNumber;\n state.completed.pageSize = payload.pageSize;\n state.completed.totalCount = payload.totalCount;\n state.completed.pagesCount = payload.pagesCount;\n },\n\n setFetchErrorForCompletedList: (state, payload:string) => {\n state.completed.isFetching = false;\n state.completed.fetchError = payload;\n },\n\n\n updateAuction: (state, auction:Auction_ModelTypeDef) => {\n const existingAuction = state.byId.get(auction.id);\n\n const updatedAuctionList = auction.isCompleted ? state.completed.list : state.active.list;\n const updatedAuction = {\n ... existingAuction, // may be null\n ... auction, // overwrite with new info\n }\n\n if (! existingAuction) {\n // existing Auction not found\n // then just add\n updatedAuctionList.push(auction);\n }\n\n else {\n // existing Auction found\n let existingAuctionList = existingAuction.isCompleted ? state.completed.list : state.active.list;\n let existingAuctionListIndex = existingAuctionList.findIndex(a => a.id === auction.id);\n\n // need to change list to/from completed <-> active ?\n if (existingAuction.isCompleted !== updatedAuction.isCompleted) {\n // remove from old list\n existingAuctionList.splice(existingAuctionListIndex, 1);\n // add to new list\n updatedAuctionList.push(updatedAuction);\n }\n else {\n // update\n existingAuctionList[existingAuctionListIndex] = updatedAuction;\n }\n }\n\n if (updatedAuction.isCompleted) {\n updatedAuctionList.sort((a1, a2) => {\n // when COMPLETED: sort descending by completesAt\n return a2.completesAt.toSeconds() - a1.completesAt.toSeconds();\n })\n }\n else {\n updatedAuctionList.sort((a1, a2) => (\n a1.completesAt.toSeconds() - a2.completesAt.toSeconds() ||\n a1.startsAt.toSeconds() - a2.startsAt.toSeconds() ||\n a1.id - a2.id))\n }\n\n // add to Map\n state.byId.set(auction.id, updatedAuction);\n },\n\n\n removeAuction: (state, {auctionId}:{ auctionId:number }) => {\n console.log('>>>>removeAuction: ', auctionId, state);\n state.active.list = state.active.list.filter(a => a.id !== auctionId);\n state.completed.list = state.completed.list.filter(a => a.id !== auctionId);\n state.byId.delete(auctionId);\n },\n },\n\n\n effects: (dispatch) => ({\n\n async loadActiveAuctionsList(browserParams?: ListingBrowserParams) {\n try {\n const auctionsList: PaginatedList_TypeDef = await AppController.instance.remoteDataHandler.fetchAuctionsList({\n ...browserParams,\n completesAt: 1,\n entityDetailsLevel: ApiResourceDetailsLevelsEnum.minimal\n });\n dispatch.auctionsLists.setFetchedActiveList(auctionsList);\n }\n catch (ex) {\n dispatch.auctionsLists.setFetchErrorForActiveList(ex.toString());\n }\n },\n\n\n async loadCompletedAuctionsList(browserParams?: ListingBrowserParams) {\n try {\n const auctionsList: PaginatedList_TypeDef = await AppController.instance.remoteDataHandler.fetchAuctionsList({\n ...browserParams,\n completesAt: -1,\n entityDetailsLevel: ApiResourceDetailsLevelsEnum.minimal\n });\n dispatch.auctionsLists.setFetchedCompletedList(auctionsList);\n }\n catch (ex) {\n dispatch.auctionsLists.setFetchErrorForCompletedList(ex.toString());\n }\n },\n\n\n async reloadAuction({auctionId, details = ApiResourceDetailsLevelsEnum.minimal}:{auctionId:number, details?:ApiResourceDetailsLevelsEnum}, rootState) {\n try {\n const auction:Auction_ModelTypeDef = await AppController.instance.remoteDataHandler.fetchAuction(auctionId, details);\n dispatch.auctionsLists.updateAuction(auction);\n\n // update \"currentAuction\" if it's the same (by id)\n if (auctionId === rootState.currentAuction?.auction?.id) {\n dispatch.currentAuction.updateAuction(auction);\n }\n }\n catch (ex) {\n //???\n }\n }\n\n }),\n});\n", "\nexport type PropertyMergerFunction = (existingValue:T, updateValue:T)=>T;\n\n\n\nexport const genericNotUndefinedValueMergerFn:PropertyMergerFunction = (existingValue, updateValue) => {\n // the non-undefined value will be resulted\n return (existingValue !== undefined)\n ? (updateValue !== undefined ? updateValue : existingValue)\n : updateValue;\n}\n\n\n", "import {Auction_ModelTypeDef} from \"../../../type_defs/model\";\nimport {ApiResourceDetailsLevelsEnum} from \"../../../type_defs/api\";\nimport {genericNotUndefinedValueMergerFn, PropertyMergerFunction} from \"./commonHelpers\";\nimport {TaggedLogger} from \"../../../utilities\";\n\nconst _logger = TaggedLogger.get('auctionsHelper');\n\n/**\n * \"mergers\" (aka properties mergers) are functions that contain the logic how to update an existing value\n */\n\nconst AuctionPropertiesMergers:{ [key:string]:PropertyMergerFunction } = {\n\n _detailsLevel: (eVal:null|ApiResourceDetailsLevelsEnum, uVal:ApiResourceDetailsLevelsEnum|null):ApiResourceDetailsLevelsEnum => {\n // details level is \"additive\", meaning that for example: \"full\" overwrites \"medium\", but \"medium\" cannot overwrite \"full\"\n\n if (! eVal) {\n return uVal;\n }\n else if (! uVal) {\n return eVal;\n }\n\n if (eVal === ApiResourceDetailsLevelsEnum.full) {\n return eVal;\n }\n if (uVal === ApiResourceDetailsLevelsEnum.full) {\n return uVal;\n }\n if (eVal === ApiResourceDetailsLevelsEnum.minimal) {\n return eVal;\n }\n if (uVal === ApiResourceDetailsLevelsEnum.minimal) {\n return uVal;\n }\n return ApiResourceDetailsLevelsEnum.minimal\n }\n}\n\n\n\n\n\nexport const mergeAuction = (existingAuction:Auction_ModelTypeDef, updateAuction:Partial):Auction_ModelTypeDef => {\n const resultAuction:Auction_ModelTypeDef = {\n ... existingAuction\n }\n\n if (updateAuction) {\n const safeExistingAuction = existingAuction || {};\n Object.entries(updateAuction).forEach(([propKey, updateValue]) => {\n const mergerFn = AuctionPropertiesMergers[propKey] || genericNotUndefinedValueMergerFn;\n const existingValue = safeExistingAuction[propKey];\n resultAuction[propKey] = mergerFn(existingValue, updateValue);\n })\n }\n\n return resultAuction;\n};\n\n\n\n\n\n", "import {mergeAuction} from \"./auctionsHelpers\";\n\nconst ModelsHelpers = {\n\n mergeAuction,\n}\n\nexport default ModelsHelpers;\n", "import {createModel} from \"@rematch/core\";\nimport {RootModel} from \"./index\";\nimport {Auction_ModelTypeDef} from \"../../type_defs/model\";\nimport AppController from \"../../AppController\";\nimport {ApiResourceDetailsLevelsEnum, BiddingWarrantStateCode_Enum} from \"../../type_defs/api\";\nimport StaticModelsAndConstants from \"../../StaticModelsAndConstants\";\nimport ModelsHelpers from \"./helpers\";\n\n\nexport type CurrentAuctionModelState = {\n auctionId: number,\n auction: Auction_ModelTypeDef,\n\n isFetching?: boolean,\n hasFetchError?: string|boolean,\n\n isTimedFastBiddingAvailable?: boolean,\n}\n\nexport const currentAuction = createModel()({\n name: 'currentAuction',\n\n state: {\n auctionId: null,\n auction: null,\n isFetching: true,\n } as CurrentAuctionModelState,\n\n reducers: {\n setAuctionByReplace: (state, payload:Auction_ModelTypeDef) => {\n state.auction = payload;\n state.auctionId = payload?.id;\n if (state.auction) {\n state.auction.completesAtDiffNowMinutes = Math.floor(state.auction.completesAt.diffNow().as('minutes'));\n state.isTimedFastBiddingAvailable = state.auction.auctionType.isTimed && state.auction.timedLotsStaggeringOffsetSeconds &&\n state.auction.timelineState.isRunning && (state.auction.closingStartsAt.diffNow().as('minutes') < 15);\n }\n state.isFetching = false;\n state.hasFetchError = null;\n },\n\n updateAuction: (state, payload:Partial) => {\n state.auction = ModelsHelpers.mergeAuction(state.auction, payload);\n state.auction.completesAtDiffNowMinutes = Math.floor(state.auction.completesAt.diffNow().as('minutes'));\n state.isTimedFastBiddingAvailable = state.auction.auctionType.isTimed && state.auction.timedLotsStaggeringOffsetSeconds &&\n state.auction.timelineState.isRunning && (state.auction.closingStartsAt.diffNow().as('minutes') < 15);\n state.isFetching = false;\n state.hasFetchError = null;\n },\n\n\n setIsFetching: (state, payload:boolean = true) => {\n state.isFetching = payload;\n },\n\n setFetchError: (state, payload:string|boolean) => {\n state.isFetching = false;\n state.hasFetchError = payload;\n },\n\n\n updateMyBiddingWarrantStateByCode: (state, newWarrantStateCode:BiddingWarrantStateCode_Enum) => {\n state.auction.myBiddingWarrantState = StaticModelsAndConstants.BiddingWarrantStates.getByCode(newWarrantStateCode);\n },\n },\n\n\n effects: (dispatch) => ({\n\n async asyncFetchLoad({ auctionId, detailsLevel = ApiResourceDetailsLevelsEnum.full }:{ auctionId:number, detailsLevel?:ApiResourceDetailsLevelsEnum }, rootState) {\n try {\n dispatch.currentAuction.setIsFetching(true);\n const fetchedAuction = await AppController.instance.remoteDataHandler.fetchAuction(auctionId, detailsLevel);\n\n if (rootState.currentAuction.auction?.id === fetchedAuction.id) {\n dispatch.currentAuction.updateAuction(fetchedAuction);\n }\n else {\n dispatch.currentAuction.setAuctionByReplace(fetchedAuction);\n }\n }\n catch (ex) {\n dispatch.currentAuction.setFetchError(ex.toString() || true);\n }\n },\n\n }),\n\n})\n", "import {createModel} from \"@rematch/core\";\nimport {RootModel} from \"./index\";\nimport AppController from \"../../AppController\";\nimport {\n CatalogLot_ModelTypeDef,\n LotMetal_ModelTypeDef,\n ListingBrowserParams,\n LotsPaginatedList_TypeDef,\n LotsRunningTimedStaggeredList_TypeDef,\n RunningCatalogLot_ModelTypeDef,\n RunningLotMetal_ModelTypeDef\n} from \"../../type_defs/model\";\nimport {ApiResource_LotMetal, ApiResource_RunningTimedLot, ApiResourceDetailsLevelsEnum} from \"../../type_defs/api\";\nimport {TaggedLogger} from \"../../utilities\";\n\n\nconst _logger = TaggedLogger.get('currentAuctionLotsModel');\n\nexport enum LotsViewModes_Enum {\n grid = 'grid',\n list = 'list',\n fastBidding = 'fastBidding',\n}\n\n\nexport type CurrentAuctionLotsModelState = {\n\n lotInFocus?: RunningCatalogLot_ModelTypeDef, // used for the full-page single lot view\n\n lotsList: RunningCatalogLot_ModelTypeDef[]|null,\n lotsById: Map,\n\n searchQuery?:string,\n sortingCriteria?:string,\n\n refTimestamp?: number,\n cursorTimestamp?: number,\n nextCursorTimestamp?: number,\n windowCount?: number,\n\n pageNumber: number,\n pageSize?: number,\n pagesCount: number,\n\n totalCount: number,\n\n isInitialFetching: boolean,\n isFetching: boolean,\n hasFetchError?: string|boolean,\n}\n\nexport const currentAuctionLots = createModel()({\n name: 'currentAuctionLots',\n\n state: {\n isInitialFetching: true,\n isFetching: true,\n\n lotsList: [],\n lotsById: new Map(),\n\n totalCount: 0,\n pageNumber: 1,\n pagesCount: 1,\n } as CurrentAuctionLotsModelState,\n\n reducers: {\n resetDataBeforeInitialFetch: (state, payload?) => {\n state.isInitialFetching = true;\n state.isFetching = true;\n state.hasFetchError = null;\n\n state.lotsList = [];\n state.lotsById = new Map();\n state.lotInFocus = null;\n\n state.refTimestamp = 0;\n state.cursorTimestamp = 0;\n state.nextCursorTimestamp = 0;\n state.pageNumber = 1;\n state.totalCount = 0;\n state.pagesCount = 0;\n },\n\n initForTimedStaggeredFastBiddingView: (state, apiResponseData:LotsRunningTimedStaggeredList_TypeDef) => {\n state.isInitialFetching = false;\n state.isFetching = true;\n state.hasFetchError = null;\n\n state.lotsList = [];\n state.lotsById = new Map();\n state.lotInFocus = null;\n\n state.refTimestamp = 0;\n state.cursorTimestamp = 0;\n state.nextCursorTimestamp = 0;\n state.pageNumber = 1;\n state.totalCount = 0;\n state.pagesCount = 0;\n\n mutateStateForTimedStaggeredFastBiddingView(state, apiResponseData);\n },\n\n appendForTimedStaggeredFastBiddingView: (state, apiResponseData:LotsRunningTimedStaggeredList_TypeDef) => {\n mutateStateForTimedStaggeredFastBiddingView(state, apiResponseData);\n },\n\n setViewList: (state, payload:LotsPaginatedList_TypeDef) => {\n state.isInitialFetching = false;\n state.isFetching = false;\n state.hasFetchError = null;\n\n state.lotsList = payload.list;\n\n state.refTimestamp = 0;\n state.cursorTimestamp = 0;\n\n state.pageNumber = payload.pageNumber;\n state.pageSize = payload.pageSize;\n state.totalCount = payload.totalCount;\n state.pagesCount = payload.pagesCount;\n },\n\n\n setViewLotInFocus: (state, payload:CatalogLot_ModelTypeDef) => {\n state.isInitialFetching = false;\n state.isFetching = false;\n state.hasFetchError = null;\n\n state.lotInFocus = payload;\n },\n\n\n updateViewLotInFocus: (state, payload:CatalogLot_ModelTypeDef) => {\n state.lotInFocus = {\n ... state.lotInFocus,\n ... payload,\n };\n state.isFetching = false;\n state.hasFetchError = null;\n },\n\n\n setIsFetching: (state, payload:boolean = true) => {\n state.isFetching = payload;\n },\n\n setFetchError: (state, payload:string|boolean) => {\n state.isInitialFetching = false;\n state.isFetching = false;\n state.hasFetchError = payload;\n },\n\n updateLotWithFullDetails: (state, payloadLotWithFullDetails:CatalogLot_ModelTypeDef) => {\n if (state.lotInFocus) {\n Object.assign(state.lotInFocus, payloadLotWithFullDetails);\n }\n else {\n state.lotsList?.forEach((sLot) => {\n if (sLot.id === payloadLotWithFullDetails.id) {\n Object.assign(sLot, payloadLotWithFullDetails);\n return\n }\n });\n }\n },\n\n updateLotsListWithFullDetails: (state, payloadListLotsWithFullDetails: Array): void => {\n payloadListLotsWithFullDetails.forEach((pLot) => {\n state.lotsList?.forEach((sLot) => {\n if (sLot.id === pLot.id) {\n Object.assign(sLot, pLot);\n return\n }\n });\n });\n },\n\n\n updateRunningLotAndExtendLinkedLots: (state, payloadLot:RunningLotMetal_ModelTypeDef) => {\n if (state.lotInFocus) {\n mutateRunningLotWithBidAndLinkedGroupExtension(state.lotInFocus, payloadLot);\n }\n else {\n state.lotsList?.forEach((sLot) => {\n mutateRunningLotWithBidAndLinkedGroupExtension(sLot, payloadLot);\n });\n }\n },\n\n\n updateLotWithChangedInterest: (state, payloadLot:LotMetal_ModelTypeDef) => {\n if (state.lotInFocus) {\n state.lotInFocus.myWatched = payloadLot.myWatched;\n }\n else {\n state.lotsList?.forEach((sLot) => {\n if (sLot.id === payloadLot.id) {\n sLot.myWatched = payloadLot.myWatched;\n }\n });\n }\n },\n\n\n updateLotSetHiddenFromView: (state, lotId:number) => {\n const idx = state.lotsList.findIndex(lot => lot.id == lotId);\n if (idx > -1) {\n state.lotsList[idx].isHiddenFromLotsListView = true;\n }\n }\n },\n\n\n effects: (dispatch) => ({\n\n\n async asyncLoadForSingleLotView(params:{ lotId: number, detailsLevel?:ApiResourceDetailsLevelsEnum }, rootState) {\n try {\n const { lotId } = params;\n const auctionId = rootState.currentAuction.auctionId;\n\n if (rootState.currentAuctionLots.lotInFocus?.id !== lotId) {\n // cleanup previously loaded lot if exists\n dispatch.currentAuctionLots.setViewLotInFocus(null);\n }\n\n dispatch.currentAuctionLots.setIsFetching(true);\n\n const [responseDataLot, responseDataMediaFiles] = await Promise.all([\n AppController.instance.remoteDataHandler.fetchAuctionLot(auctionId, lotId, params.detailsLevel || ApiResourceDetailsLevelsEnum.full),\n AppController.instance.remoteDataHandler.fetchAuctionLotItemMediaFilesList(auctionId, lotId)\n ]);\n\n if (rootState.currentAuctionLots.lotInFocus?.id === responseDataLot.id) {\n dispatch.currentAuctionLots.updateViewLotInFocus({\n ... responseDataLot,\n mediaFiles: responseDataMediaFiles.list,\n });\n }\n else {\n dispatch.currentAuctionLots.setViewLotInFocus({\n ... responseDataLot,\n mediaFiles: responseDataMediaFiles.list,\n });\n }\n\n }\n catch (ex) {\n dispatch.currentAuctionLots.setFetchError(ex.toString() || true);\n }\n },\n\n\n async asyncLoadForBrowsableView(params:ListingBrowserParams = { pageNumber: 1 }, rootState) {\n try {\n dispatch.currentAuctionLots.setIsFetching(true);\n\n if (params.entityDetailsLevel === ApiResourceDetailsLevelsEnum.full) {\n // sort-of-HACK for lots ListView, when we fetch with full details, we first make a call to fetch the minimal information,\n let responseData = await AppController.instance.remoteDataHandler\n .fetchAuctionLotsListBrowsable(rootState.currentAuction.auctionId, {\n ... params,\n entityDetailsLevel: ApiResourceDetailsLevelsEnum.minimal,\n })\n\n dispatch.currentAuctionLots.setViewList(responseData);\n\n // then, we make a subsequent call for the full details information\n try {\n responseData = await AppController.instance.remoteDataHandler\n .fetchAuctionLotsListBrowsable(rootState.currentAuction.auctionId, params);\n dispatch.currentAuctionLots.updateLotsListWithFullDetails(responseData.list);\n }\n catch (ex) {\n // silent fail, we should NOT set the fetch error, it will break the view\n }\n }\n else {\n const responseData = await AppController.instance.remoteDataHandler\n .fetchAuctionLotsListBrowsable(rootState.currentAuction.auctionId, params)\n\n dispatch.currentAuctionLots.setViewList(responseData);\n }\n }\n catch (ex) {\n dispatch.currentAuctionLots.setFetchError(ex.toString() || true);\n }\n },\n\n\n\n async asyncInitLoadForTimedStaggeredFastBiddingView(_params?, rootState?) {\n try {\n const responseData = await AppController.instance.remoteDataHandler.fetchAuctionLotsRunningTimedStaggeredPaginatedList(rootState.currentAuction.auctionId);\n\n dispatch.currentAuctionLots.initForTimedStaggeredFastBiddingView(responseData);\n }\n catch (ex) {\n dispatch.currentAuctionLots.setFetchError(ex.toString() || true);\n }\n },\n\n\n async asyncLoadMoreForTimedStaggeredFastBiddingView(_params?, rootState?) {\n try {\n dispatch.currentAuctionLots.setIsFetching(true);\n\n const responseData = await AppController.instance.remoteDataHandler.fetchAuctionLotsRunningTimedStaggeredPaginatedList(rootState.currentAuction.auctionId,\n rootState.currentAuctionLots.refTimestamp,\n rootState.currentAuctionLots.nextCursorTimestamp,\n );\n\n dispatch.currentAuctionLots.appendForTimedStaggeredFastBiddingView(responseData);\n }\n catch (ex) {\n dispatch.currentAuctionLots.setFetchError(ex.toString() || true);\n }\n },\n\n\n\n\n async asyncFetchAndUpdateRunningLotWithSideEffects({auctionId, lotId}:{auctionId:number, lotId:number}, rootState) {\n\n // fetch RunningLot via API\n const updatedRunningLot:RunningLotMetal_ModelTypeDef =\n await AppController.instance.remoteDataHandler.fetchAuctionLot(auctionId, lotId);\n\n const auctionCompletesAt = rootState.currentAuction?.auction?.completesAt;\n // update Auction completion time if it's before the updated Lot\n if (auctionCompletesAt && auctionCompletesAt < updatedRunningLot.completesAt) {\n dispatch.currentAuction.updateAuction({ completesAt: updatedRunningLot.completesAt, isCompleted: false });\n }\n\n dispatch.currentAuctionLots.updateRunningLotAndExtendLinkedLots(updatedRunningLot);\n dispatch.watchlist.updateRunningLotAndExtendLinkedLots(updatedRunningLot);\n },\n\n\n\n async asyncFetchAndUpdateLotWithFullDetails({lotId}:{lotId:number}, rootState) {\n // _logger.debug('.asyncFetchAndUpdateLotWithFullDetails: lotId:', lotId);\n\n const auctionId = rootState.currentAuction.auctionId;\n\n const [responseDataLot, responseDataMediaFiles] = await Promise.all([\n AppController.instance.remoteDataHandler.fetchAuctionLot(auctionId, lotId, ApiResourceDetailsLevelsEnum.full),\n AppController.instance.remoteDataHandler.fetchAuctionLotItemMediaFilesList(auctionId, lotId)\n ]);\n\n const lotWithFullDetails:CatalogLot_ModelTypeDef = {\n ... responseDataLot,\n mediaFiles: responseDataMediaFiles.list,\n }\n\n dispatch.currentAuctionLots.updateLotWithFullDetails(lotWithFullDetails);\n },\n\n\n\n async asyncFetchAndUpdateLotChangedInterest({lotId}:{lotId:number}, rootState) {\n const auctionId = rootState.currentAuction.auctionId;\n\n // fetch Lot via API\n const updatedLot:LotMetal_ModelTypeDef =\n await AppController.instance.remoteDataHandler.fetchAuctionLot(auctionId, lotId, ApiResourceDetailsLevelsEnum.metal);\n\n dispatch.currentAuctionLots.updateLotWithChangedInterest(updatedLot);\n },\n\n\n }),\n})\n\n\n\n\nfunction mutateStateForTimedStaggeredFastBiddingView(state, apiResponseData:LotsRunningTimedStaggeredList_TypeDef) {\n state.isFetching = false;\n state.hasFetchError = null;\n\n state.totalCount = apiResponseData.totalCount;\n\n state.refTimestamp = apiResponseData.refTimestamp;\n state.cursorTimestamp = apiResponseData.cursorTimestamp;\n state.nextCursorTimestamp = apiResponseData.nextCursorTimestamp;\n\n apiResponseData.list.forEach((lot) => {\n if (lot.isCompleted) {\n return; // skip completed lots\n }\n if (state.lotsById.has(lot.id)) {\n return; // skip already existing lots\n }\n state.lotsList.push(lot);\n state.lotsById.set(lot.id, lot);\n });\n}\n\n\n\nfunction mutateRunningLotWithBidAndLinkedGroupExtension(mutableSourceLot:RunningLotMetal_ModelTypeDef, payloadLot:RunningLotMetal_ModelTypeDef) {\n const { id, linkedLotsGroupId, completesAt, isCompleted } = payloadLot;\n const completesAtSeconds = completesAt.toSeconds();\n\n if (mutableSourceLot.id === id) {\n mutableSourceLot.bidsCount = payloadLot.bidsCount;\n mutableSourceLot.askingBidAmountCents = payloadLot.askingBidAmountCents;\n mutableSourceLot.leadingBidAmountCents = payloadLot.leadingBidAmountCents;\n mutableSourceLot.myBidIsLeadingBid = payloadLot.myBidIsLeadingBid;\n mutableSourceLot.myMaxBidAmountCents = payloadLot.myMaxBidAmountCents;\n mutableSourceLot.myBidExistsInHistory = payloadLot.myBidExistsInHistory;\n mutableSourceLot.reservePriceStatusCode = payloadLot.reservePriceStatusCode;\n\n if (mutableSourceLot.completesAt.toSeconds() !== completesAtSeconds || mutableSourceLot.isCompleted !== isCompleted) {\n mutableSourceLot.completesAt = completesAt;\n mutableSourceLot.isCompleted = isCompleted;\n mutableSourceLot.hasRound = payloadLot.hasRound;\n }\n }\n else if (linkedLotsGroupId && mutableSourceLot.linkedLotsGroupId === linkedLotsGroupId) {\n if (mutableSourceLot.completesAt.toSeconds() !== completesAtSeconds || mutableSourceLot.isCompleted !== isCompleted) {\n mutableSourceLot.completesAt = completesAt;\n mutableSourceLot.isCompleted = isCompleted;\n }\n }\n}\n", "/**\n * @license\n * Lodash \n * Copyright OpenJS Foundation and other contributors \n * Released under MIT license \n * Based on Underscore.js 1.8.3 \n * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors\n */\n;(function() {\n\n /** Used as a safe reference for `undefined` in pre-ES5 environments. */\n var undefined;\n\n /** Used as the semantic version number. */\n var VERSION = '4.17.21';\n\n /** Used as the size to enable large array optimizations. */\n var LARGE_ARRAY_SIZE = 200;\n\n /** Error message constants. */\n var CORE_ERROR_TEXT = 'Unsupported core-js use. Try https://npms.io/search?q=ponyfill.',\n FUNC_ERROR_TEXT = 'Expected a function',\n INVALID_TEMPL_VAR_ERROR_TEXT = 'Invalid `variable` option passed into `_.template`';\n\n /** Used to stand-in for `undefined` hash values. */\n var HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n /** Used as the maximum memoize cache size. */\n var MAX_MEMOIZE_SIZE = 500;\n\n /** Used as the internal argument placeholder. */\n var PLACEHOLDER = '__lodash_placeholder__';\n\n /** Used to compose bitmasks for cloning. */\n var CLONE_DEEP_FLAG = 1,\n CLONE_FLAT_FLAG = 2,\n CLONE_SYMBOLS_FLAG = 4;\n\n /** Used to compose bitmasks for value comparisons. */\n var COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n /** Used to compose bitmasks for function metadata. */\n var WRAP_BIND_FLAG = 1,\n WRAP_BIND_KEY_FLAG = 2,\n WRAP_CURRY_BOUND_FLAG = 4,\n WRAP_CURRY_FLAG = 8,\n WRAP_CURRY_RIGHT_FLAG = 16,\n WRAP_PARTIAL_FLAG = 32,\n WRAP_PARTIAL_RIGHT_FLAG = 64,\n WRAP_ARY_FLAG = 128,\n WRAP_REARG_FLAG = 256,\n WRAP_FLIP_FLAG = 512;\n\n /** Used as default options for `_.truncate`. */\n var DEFAULT_TRUNC_LENGTH = 30,\n DEFAULT_TRUNC_OMISSION = '...';\n\n /** Used to detect hot functions by number of calls within a span of milliseconds. */\n var HOT_COUNT = 800,\n HOT_SPAN = 16;\n\n /** Used to indicate the type of lazy iteratees. */\n var LAZY_FILTER_FLAG = 1,\n LAZY_MAP_FLAG = 2,\n LAZY_WHILE_FLAG = 3;\n\n /** Used as references for various `Number` constants. */\n var INFINITY = 1 / 0,\n MAX_SAFE_INTEGER = 9007199254740991,\n MAX_INTEGER = 1.7976931348623157e+308,\n NAN = 0 / 0;\n\n /** Used as references for the maximum length and index of an array. */\n var MAX_ARRAY_LENGTH = 4294967295,\n MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1,\n HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1;\n\n /** Used to associate wrap methods with their bit flags. */\n var wrapFlags = [\n ['ary', WRAP_ARY_FLAG],\n ['bind', WRAP_BIND_FLAG],\n ['bindKey', WRAP_BIND_KEY_FLAG],\n ['curry', WRAP_CURRY_FLAG],\n ['curryRight', WRAP_CURRY_RIGHT_FLAG],\n ['flip', WRAP_FLIP_FLAG],\n ['partial', WRAP_PARTIAL_FLAG],\n ['partialRight', WRAP_PARTIAL_RIGHT_FLAG],\n ['rearg', WRAP_REARG_FLAG]\n ];\n\n /** `Object#toString` result references. */\n var argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n asyncTag = '[object AsyncFunction]',\n boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n domExcTag = '[object DOMException]',\n errorTag = '[object Error]',\n funcTag = '[object Function]',\n genTag = '[object GeneratorFunction]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n nullTag = '[object Null]',\n objectTag = '[object Object]',\n promiseTag = '[object Promise]',\n proxyTag = '[object Proxy]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n symbolTag = '[object Symbol]',\n undefinedTag = '[object Undefined]',\n weakMapTag = '[object WeakMap]',\n weakSetTag = '[object WeakSet]';\n\n var 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 match empty string literals in compiled template source. */\n var reEmptyStringLeading = /\\b__p \\+= '';/g,\n reEmptyStringMiddle = /\\b(__p \\+=) '' \\+/g,\n reEmptyStringTrailing = /(__e\\(.*?\\)|\\b__t\\)) \\+\\n'';/g;\n\n /** Used to match HTML entities and HTML characters. */\n var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g,\n reUnescapedHtml = /[&<>\"']/g,\n reHasEscapedHtml = RegExp(reEscapedHtml.source),\n reHasUnescapedHtml = RegExp(reUnescapedHtml.source);\n\n /** Used to match template delimiters. */\n var reEscape = /<%-([\\s\\S]+?)%>/g,\n reEvaluate = /<%([\\s\\S]+?)%>/g,\n reInterpolate = /<%=([\\s\\S]+?)%>/g;\n\n /** Used to match property names within property paths. */\n var reIsDeepProp = /\\.|\\[(?:[^[\\]]*|([\"'])(?:(?!\\1)[^\\\\]|\\\\.)*?\\1)\\]/,\n reIsPlainProp = /^\\w*$/,\n rePropName = /[^.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))/g;\n\n /**\n * Used to match `RegExp`\n * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).\n */\n var reRegExpChar = /[\\\\^$.*+?()[\\]{}|]/g,\n reHasRegExpChar = RegExp(reRegExpChar.source);\n\n /** Used to match leading whitespace. */\n var reTrimStart = /^\\s+/;\n\n /** Used to match a single whitespace character. */\n var reWhitespace = /\\s/;\n\n /** Used to match wrap detail comments. */\n var reWrapComment = /\\{(?:\\n\\/\\* \\[wrapped with .+\\] \\*\\/)?\\n?/,\n reWrapDetails = /\\{\\n\\/\\* \\[wrapped with (.+)\\] \\*/,\n reSplitDetails = /,? & /;\n\n /** Used to match words composed of alphanumeric characters. */\n var reAsciiWord = /[^\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\x7f]+/g;\n\n /**\n * Used to validate the `validate` option in `_.template` variable.\n *\n * Forbids characters which could potentially change the meaning of the function argument definition:\n * - \"(),\" (modification of function parameters)\n * - \"=\" (default value)\n * - \"[]{}\" (destructuring of function parameters)\n * - \"/\" (beginning of a comment)\n * - whitespace\n */\n var reForbiddenIdentifierChars = /[()=,{}\\[\\]\\/\\s]/;\n\n /** Used to match backslashes in property paths. */\n var reEscapeChar = /\\\\(\\\\)?/g;\n\n /**\n * Used to match\n * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components).\n */\n var reEsTemplate = /\\$\\{([^\\\\}]*(?:\\\\.[^\\\\}]*)*)\\}/g;\n\n /** Used to match `RegExp` flags from their coerced string values. */\n var reFlags = /\\w*$/;\n\n /** Used to detect bad signed hexadecimal string values. */\n var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;\n\n /** Used to detect binary string values. */\n var reIsBinary = /^0b[01]+$/i;\n\n /** Used to detect host constructors (Safari). */\n var reIsHostCtor = /^\\[object .+?Constructor\\]$/;\n\n /** Used to detect octal string values. */\n var reIsOctal = /^0o[0-7]+$/i;\n\n /** Used to detect unsigned integer values. */\n var reIsUint = /^(?:0|[1-9]\\d*)$/;\n\n /** Used to match Latin Unicode letters (excluding mathematical operators). */\n var reLatin = /[\\xc0-\\xd6\\xd8-\\xf6\\xf8-\\xff\\u0100-\\u017f]/g;\n\n /** Used to ensure capturing order of template delimiters. */\n var reNoMatch = /($^)/;\n\n /** Used to match unescaped characters in compiled string literals. */\n var reUnescapedString = /['\\n\\r\\u2028\\u2029\\\\]/g;\n\n /** Used to compose unicode character classes. */\n var rsAstralRange = '\\\\ud800-\\\\udfff',\n rsComboMarksRange = '\\\\u0300-\\\\u036f',\n reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,\n rsDingbatRange = '\\\\u2700-\\\\u27bf',\n rsLowerRange = 'a-z\\\\xdf-\\\\xf6\\\\xf8-\\\\xff',\n rsMathOpRange = '\\\\xac\\\\xb1\\\\xd7\\\\xf7',\n rsNonCharRange = '\\\\x00-\\\\x2f\\\\x3a-\\\\x40\\\\x5b-\\\\x60\\\\x7b-\\\\xbf',\n rsPunctuationRange = '\\\\u2000-\\\\u206f',\n rsSpaceRange = ' \\\\t\\\\x0b\\\\f\\\\xa0\\\\ufeff\\\\n\\\\r\\\\u2028\\\\u2029\\\\u1680\\\\u180e\\\\u2000\\\\u2001\\\\u2002\\\\u2003\\\\u2004\\\\u2005\\\\u2006\\\\u2007\\\\u2008\\\\u2009\\\\u200a\\\\u202f\\\\u205f\\\\u3000',\n rsUpperRange = 'A-Z\\\\xc0-\\\\xd6\\\\xd8-\\\\xde',\n rsVarRange = '\\\\ufe0e\\\\ufe0f',\n rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange;\n\n /** Used to compose unicode capture groups. */\n var rsApos = \"['\\u2019]\",\n rsAstral = '[' + rsAstralRange + ']',\n rsBreak = '[' + rsBreakRange + ']',\n rsCombo = '[' + rsComboRange + ']',\n rsDigits = '\\\\d+',\n rsDingbat = '[' + rsDingbatRange + ']',\n rsLower = '[' + rsLowerRange + ']',\n rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']',\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 rsUpper = '[' + rsUpperRange + ']',\n rsZWJ = '\\\\u200d';\n\n /** Used to compose unicode regexes. */\n var rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')',\n rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')',\n rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?',\n rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?',\n reOptMod = rsModifier + '?',\n rsOptVar = '[' + rsVarRange + ']?',\n rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',\n rsOrdLower = '\\\\d*(?:1st|2nd|3rd|(?![123])\\\\dth)(?=\\\\b|[A-Z_])',\n rsOrdUpper = '\\\\d*(?:1ST|2ND|3RD|(?![123])\\\\dTH)(?=\\\\b|[a-z_])',\n rsSeq = rsOptVar + reOptMod + rsOptJoin,\n rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq,\n rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';\n\n /** Used to match apostrophes. */\n var reApos = RegExp(rsApos, 'g');\n\n /**\n * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and\n * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols).\n */\n var reComboMark = RegExp(rsCombo, 'g');\n\n /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */\n var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');\n\n /** Used to match complex or compound words. */\n var reUnicodeWord = RegExp([\n rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')',\n rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')',\n rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower,\n rsUpper + '+' + rsOptContrUpper,\n rsOrdUpper,\n rsOrdLower,\n rsDigits,\n rsEmoji\n ].join('|'), 'g');\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/). */\n var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']');\n\n /** Used to detect strings that need a more robust regexp to match words. */\n var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/;\n\n /** Used to assign default `context` object properties. */\n var contextProps = [\n 'Array', 'Buffer', 'DataView', 'Date', 'Error', 'Float32Array', 'Float64Array',\n 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Map', 'Math', 'Object',\n 'Promise', 'RegExp', 'Set', 'String', 'Symbol', 'TypeError', 'Uint8Array',\n 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap',\n '_', 'clearTimeout', 'isFinite', 'parseInt', 'setTimeout'\n ];\n\n /** Used to make template sourceURLs easier to identify. */\n var templateCounter = -1;\n\n /** Used to identify `toStringTag` values of typed arrays. */\n var typedArrayTags = {};\n typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =\n typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =\n typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =\n typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =\n typedArrayTags[uint32Tag] = true;\n typedArrayTags[argsTag] = typedArrayTags[arrayTag] =\n typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =\n typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =\n typedArrayTags[errorTag] = typedArrayTags[funcTag] =\n typedArrayTags[mapTag] = typedArrayTags[numberTag] =\n typedArrayTags[objectTag] = typedArrayTags[regexpTag] =\n typedArrayTags[setTag] = typedArrayTags[stringTag] =\n typedArrayTags[weakMapTag] = false;\n\n /** Used to identify `toStringTag` values supported by `_.clone`. */\n var cloneableTags = {};\n cloneableTags[argsTag] = cloneableTags[arrayTag] =\n cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] =\n cloneableTags[boolTag] = cloneableTags[dateTag] =\n cloneableTags[float32Tag] = cloneableTags[float64Tag] =\n cloneableTags[int8Tag] = cloneableTags[int16Tag] =\n cloneableTags[int32Tag] = cloneableTags[mapTag] =\n cloneableTags[numberTag] = cloneableTags[objectTag] =\n cloneableTags[regexpTag] = cloneableTags[setTag] =\n cloneableTags[stringTag] = cloneableTags[symbolTag] =\n cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =\n cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;\n cloneableTags[errorTag] = cloneableTags[funcTag] =\n cloneableTags[weakMapTag] = false;\n\n /** Used to map Latin Unicode letters to basic Latin letters. */\n var deburredLetters = {\n // Latin-1 Supplement block.\n '\\xc0': 'A', '\\xc1': 'A', '\\xc2': 'A', '\\xc3': 'A', '\\xc4': 'A', '\\xc5': 'A',\n '\\xe0': 'a', '\\xe1': 'a', '\\xe2': 'a', '\\xe3': 'a', '\\xe4': 'a', '\\xe5': 'a',\n '\\xc7': 'C', '\\xe7': 'c',\n '\\xd0': 'D', '\\xf0': 'd',\n '\\xc8': 'E', '\\xc9': 'E', '\\xca': 'E', '\\xcb': 'E',\n '\\xe8': 'e', '\\xe9': 'e', '\\xea': 'e', '\\xeb': 'e',\n '\\xcc': 'I', '\\xcd': 'I', '\\xce': 'I', '\\xcf': 'I',\n '\\xec': 'i', '\\xed': 'i', '\\xee': 'i', '\\xef': 'i',\n '\\xd1': 'N', '\\xf1': 'n',\n '\\xd2': 'O', '\\xd3': 'O', '\\xd4': 'O', '\\xd5': 'O', '\\xd6': 'O', '\\xd8': 'O',\n '\\xf2': 'o', '\\xf3': 'o', '\\xf4': 'o', '\\xf5': 'o', '\\xf6': 'o', '\\xf8': 'o',\n '\\xd9': 'U', '\\xda': 'U', '\\xdb': 'U', '\\xdc': 'U',\n '\\xf9': 'u', '\\xfa': 'u', '\\xfb': 'u', '\\xfc': 'u',\n '\\xdd': 'Y', '\\xfd': 'y', '\\xff': 'y',\n '\\xc6': 'Ae', '\\xe6': 'ae',\n '\\xde': 'Th', '\\xfe': 'th',\n '\\xdf': 'ss',\n // Latin Extended-A block.\n '\\u0100': 'A', '\\u0102': 'A', '\\u0104': 'A',\n '\\u0101': 'a', '\\u0103': 'a', '\\u0105': 'a',\n '\\u0106': 'C', '\\u0108': 'C', '\\u010a': 'C', '\\u010c': 'C',\n '\\u0107': 'c', '\\u0109': 'c', '\\u010b': 'c', '\\u010d': 'c',\n '\\u010e': 'D', '\\u0110': 'D', '\\u010f': 'd', '\\u0111': 'd',\n '\\u0112': 'E', '\\u0114': 'E', '\\u0116': 'E', '\\u0118': 'E', '\\u011a': 'E',\n '\\u0113': 'e', '\\u0115': 'e', '\\u0117': 'e', '\\u0119': 'e', '\\u011b': 'e',\n '\\u011c': 'G', '\\u011e': 'G', '\\u0120': 'G', '\\u0122': 'G',\n '\\u011d': 'g', '\\u011f': 'g', '\\u0121': 'g', '\\u0123': 'g',\n '\\u0124': 'H', '\\u0126': 'H', '\\u0125': 'h', '\\u0127': 'h',\n '\\u0128': 'I', '\\u012a': 'I', '\\u012c': 'I', '\\u012e': 'I', '\\u0130': 'I',\n '\\u0129': 'i', '\\u012b': 'i', '\\u012d': 'i', '\\u012f': 'i', '\\u0131': 'i',\n '\\u0134': 'J', '\\u0135': 'j',\n '\\u0136': 'K', '\\u0137': 'k', '\\u0138': 'k',\n '\\u0139': 'L', '\\u013b': 'L', '\\u013d': 'L', '\\u013f': 'L', '\\u0141': 'L',\n '\\u013a': 'l', '\\u013c': 'l', '\\u013e': 'l', '\\u0140': 'l', '\\u0142': 'l',\n '\\u0143': 'N', '\\u0145': 'N', '\\u0147': 'N', '\\u014a': 'N',\n '\\u0144': 'n', '\\u0146': 'n', '\\u0148': 'n', '\\u014b': 'n',\n '\\u014c': 'O', '\\u014e': 'O', '\\u0150': 'O',\n '\\u014d': 'o', '\\u014f': 'o', '\\u0151': 'o',\n '\\u0154': 'R', '\\u0156': 'R', '\\u0158': 'R',\n '\\u0155': 'r', '\\u0157': 'r', '\\u0159': 'r',\n '\\u015a': 'S', '\\u015c': 'S', '\\u015e': 'S', '\\u0160': 'S',\n '\\u015b': 's', '\\u015d': 's', '\\u015f': 's', '\\u0161': 's',\n '\\u0162': 'T', '\\u0164': 'T', '\\u0166': 'T',\n '\\u0163': 't', '\\u0165': 't', '\\u0167': 't',\n '\\u0168': 'U', '\\u016a': 'U', '\\u016c': 'U', '\\u016e': 'U', '\\u0170': 'U', '\\u0172': 'U',\n '\\u0169': 'u', '\\u016b': 'u', '\\u016d': 'u', '\\u016f': 'u', '\\u0171': 'u', '\\u0173': 'u',\n '\\u0174': 'W', '\\u0175': 'w',\n '\\u0176': 'Y', '\\u0177': 'y', '\\u0178': 'Y',\n '\\u0179': 'Z', '\\u017b': 'Z', '\\u017d': 'Z',\n '\\u017a': 'z', '\\u017c': 'z', '\\u017e': 'z',\n '\\u0132': 'IJ', '\\u0133': 'ij',\n '\\u0152': 'Oe', '\\u0153': 'oe',\n '\\u0149': \"'n\", '\\u017f': 's'\n };\n\n /** Used to map characters to HTML entities. */\n var htmlEscapes = {\n '&': '&',\n '<': '<',\n '>': '>',\n '\"': '"',\n \"'\": '''\n };\n\n /** Used to map HTML entities to characters. */\n var htmlUnescapes = {\n '&': '&',\n '<': '<',\n '>': '>',\n '"': '\"',\n ''': \"'\"\n };\n\n /** Used to escape characters for inclusion in compiled string literals. */\n var stringEscapes = {\n '\\\\': '\\\\',\n \"'\": \"'\",\n '\\n': 'n',\n '\\r': 'r',\n '\\u2028': 'u2028',\n '\\u2029': 'u2029'\n };\n\n /** Built-in method references without a dependency on `root`. */\n var freeParseFloat = parseFloat,\n freeParseInt = parseInt;\n\n /** Detect free variable `global` from Node.js. */\n var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;\n\n /** Detect free variable `self`. */\n var freeSelf = typeof self == 'object' && self && self.Object === Object && self;\n\n /** Used as a reference to the global object. */\n var root = freeGlobal || freeSelf || Function('return this')();\n\n /** Detect free variable `exports`. */\n var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n /** Detect free variable `module`. */\n var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n /** Detect the popular CommonJS extension `module.exports`. */\n var moduleExports = freeModule && freeModule.exports === freeExports;\n\n /** Detect free variable `process` from Node.js. */\n var freeProcess = moduleExports && freeGlobal.process;\n\n /** Used to access faster Node.js helpers. */\n var 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\n /* Node.js helper references. */\n var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer,\n nodeIsDate = nodeUtil && nodeUtil.isDate,\n nodeIsMap = nodeUtil && nodeUtil.isMap,\n nodeIsRegExp = nodeUtil && nodeUtil.isRegExp,\n nodeIsSet = nodeUtil && nodeUtil.isSet,\n nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;\n\n /*--------------------------------------------------------------------------*/\n\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 */\n function 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\n /**\n * A specialized version of `baseAggregator` for arrays.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} setter The function to set `accumulator` values.\n * @param {Function} iteratee The iteratee to transform keys.\n * @param {Object} accumulator The initial aggregated object.\n * @returns {Function} Returns `accumulator`.\n */\n function arrayAggregator(array, setter, iteratee, accumulator) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n var value = array[index];\n setter(accumulator, value, iteratee(value), array);\n }\n return accumulator;\n }\n\n /**\n * A specialized version of `_.forEach` for arrays without support for\n * iteratee 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 `array`.\n */\n function arrayEach(array, iteratee) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (iteratee(array[index], index, array) === false) {\n break;\n }\n }\n return array;\n }\n\n /**\n * A specialized version of `_.forEachRight` for arrays without support for\n * iteratee 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 `array`.\n */\n function arrayEachRight(array, iteratee) {\n var length = array == null ? 0 : array.length;\n\n while (length--) {\n if (iteratee(array[length], length, array) === false) {\n break;\n }\n }\n return array;\n }\n\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 */\n function 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\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 */\n function 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\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 */\n function arrayIncludes(array, value) {\n var length = array == null ? 0 : array.length;\n return !!length && baseIndexOf(array, value, 0) > -1;\n }\n\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 */\n function 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\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 */\n function 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\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 */\n function 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\n /**\n * A specialized version of `_.reduce` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {*} [accumulator] The initial value.\n * @param {boolean} [initAccum] Specify using the first element of `array` as\n * the initial value.\n * @returns {*} Returns the accumulated value.\n */\n function arrayReduce(array, iteratee, accumulator, initAccum) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n if (initAccum && length) {\n accumulator = array[++index];\n }\n while (++index < length) {\n accumulator = iteratee(accumulator, array[index], index, array);\n }\n return accumulator;\n }\n\n /**\n * A specialized version of `_.reduceRight` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {*} [accumulator] The initial value.\n * @param {boolean} [initAccum] Specify using the last element of `array` as\n * the initial value.\n * @returns {*} Returns the accumulated value.\n */\n function arrayReduceRight(array, iteratee, accumulator, initAccum) {\n var length = array == null ? 0 : array.length;\n if (initAccum && length) {\n accumulator = array[--length];\n }\n while (length--) {\n accumulator = iteratee(accumulator, array[length], length, array);\n }\n return accumulator;\n }\n\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 */\n function 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\n /**\n * Gets the size of an ASCII `string`.\n *\n * @private\n * @param {string} string The string inspect.\n * @returns {number} Returns the string size.\n */\n var asciiSize = baseProperty('length');\n\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 */\n function asciiToArray(string) {\n return string.split('');\n }\n\n /**\n * Splits an ASCII `string` into an array of its words.\n *\n * @private\n * @param {string} The string to inspect.\n * @returns {Array} Returns the words of `string`.\n */\n function asciiWords(string) {\n return string.match(reAsciiWord) || [];\n }\n\n /**\n * The base implementation of methods like `_.findKey` and `_.findLastKey`,\n * without support for iteratee shorthands, which iterates over `collection`\n * using `eachFunc`.\n *\n * @private\n * @param {Array|Object} collection The collection to inspect.\n * @param {Function} predicate The function invoked per iteration.\n * @param {Function} eachFunc The function to iterate over `collection`.\n * @returns {*} Returns the found element or its key, else `undefined`.\n */\n function baseFindKey(collection, predicate, eachFunc) {\n var result;\n eachFunc(collection, function(value, key, collection) {\n if (predicate(value, key, collection)) {\n result = key;\n return false;\n }\n });\n return result;\n }\n\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 */\n function 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\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 */\n function baseIndexOf(array, value, fromIndex) {\n return value === value\n ? strictIndexOf(array, value, fromIndex)\n : baseFindIndex(array, baseIsNaN, fromIndex);\n }\n\n /**\n * This function is like `baseIndexOf` except that it accepts a comparator.\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 * @param {Function} comparator The comparator invoked per element.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\n function baseIndexOfWith(array, value, fromIndex, comparator) {\n var index = fromIndex - 1,\n length = array.length;\n\n while (++index < length) {\n if (comparator(array[index], value)) {\n return index;\n }\n }\n return -1;\n }\n\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 */\n function baseIsNaN(value) {\n return value !== value;\n }\n\n /**\n * The base implementation of `_.mean` and `_.meanBy` without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {number} Returns the mean.\n */\n function baseMean(array, iteratee) {\n var length = array == null ? 0 : array.length;\n return length ? (baseSum(array, iteratee) / length) : NAN;\n }\n\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 */\n function baseProperty(key) {\n return function(object) {\n return object == null ? undefined : object[key];\n };\n }\n\n /**\n * The base implementation of `_.propertyOf` without support for deep paths.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Function} Returns the new accessor function.\n */\n function basePropertyOf(object) {\n return function(key) {\n return object == null ? undefined : object[key];\n };\n }\n\n /**\n * The base implementation of `_.reduce` and `_.reduceRight`, without support\n * for iteratee shorthands, which iterates over `collection` using `eachFunc`.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {*} accumulator The initial value.\n * @param {boolean} initAccum Specify using the first or last element of\n * `collection` as the initial value.\n * @param {Function} eachFunc The function to iterate over `collection`.\n * @returns {*} Returns the accumulated value.\n */\n function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) {\n eachFunc(collection, function(value, index, collection) {\n accumulator = initAccum\n ? (initAccum = false, value)\n : iteratee(accumulator, value, index, collection);\n });\n return accumulator;\n }\n\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 */\n function 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\n /**\n * The base implementation of `_.sum` and `_.sumBy` without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {number} Returns the sum.\n */\n function baseSum(array, iteratee) {\n var result,\n index = -1,\n length = array.length;\n\n while (++index < length) {\n var current = iteratee(array[index]);\n if (current !== undefined) {\n result = result === undefined ? current : (result + current);\n }\n }\n return result;\n }\n\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 */\n function 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\n /**\n * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array\n * of key-value pairs for `object` corresponding to the property names of `props`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array} props The property names to get values for.\n * @returns {Object} Returns the key-value pairs.\n */\n function baseToPairs(object, props) {\n return arrayMap(props, function(key) {\n return [key, object[key]];\n });\n }\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 */\n function baseTrim(string) {\n return string\n ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '')\n : string;\n }\n\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 */\n function baseUnary(func) {\n return function(value) {\n return func(value);\n };\n }\n\n /**\n * The base implementation of `_.values` and `_.valuesIn` which creates an\n * array of `object` property values corresponding to the property names\n * of `props`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array} props The property names to get values for.\n * @returns {Object} Returns the array of property values.\n */\n function baseValues(object, props) {\n return arrayMap(props, function(key) {\n return object[key];\n });\n }\n\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 */\n function cacheHas(cache, key) {\n return cache.has(key);\n }\n\n /**\n * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol\n * that is not found in the character symbols.\n *\n * @private\n * @param {Array} strSymbols The string symbols to inspect.\n * @param {Array} chrSymbols The character symbols to find.\n * @returns {number} Returns the index of the first unmatched string symbol.\n */\n function charsStartIndex(strSymbols, chrSymbols) {\n var index = -1,\n length = strSymbols.length;\n\n while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}\n return index;\n }\n\n /**\n * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol\n * that is not found in the character symbols.\n *\n * @private\n * @param {Array} strSymbols The string symbols to inspect.\n * @param {Array} chrSymbols The character symbols to find.\n * @returns {number} Returns the index of the last unmatched string symbol.\n */\n function charsEndIndex(strSymbols, chrSymbols) {\n var index = strSymbols.length;\n\n while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}\n return index;\n }\n\n /**\n * Gets the number of `placeholder` occurrences in `array`.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} placeholder The placeholder to search for.\n * @returns {number} Returns the placeholder count.\n */\n function countHolders(array, placeholder) {\n var length = array.length,\n result = 0;\n\n while (length--) {\n if (array[length] === placeholder) {\n ++result;\n }\n }\n return result;\n }\n\n /**\n * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A\n * letters to basic Latin letters.\n *\n * @private\n * @param {string} letter The matched letter to deburr.\n * @returns {string} Returns the deburred letter.\n */\n var deburrLetter = basePropertyOf(deburredLetters);\n\n /**\n * Used by `_.escape` to convert characters to HTML entities.\n *\n * @private\n * @param {string} chr The matched character to escape.\n * @returns {string} Returns the escaped character.\n */\n var escapeHtmlChar = basePropertyOf(htmlEscapes);\n\n /**\n * Used by `_.template` to escape characters for inclusion in compiled string literals.\n *\n * @private\n * @param {string} chr The matched character to escape.\n * @returns {string} Returns the escaped character.\n */\n function escapeStringChar(chr) {\n return '\\\\' + stringEscapes[chr];\n }\n\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 */\n function getValue(object, key) {\n return object == null ? undefined : object[key];\n }\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 */\n function hasUnicode(string) {\n return reHasUnicode.test(string);\n }\n\n /**\n * Checks if `string` contains a word composed of Unicode symbols.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {boolean} Returns `true` if a word is found, else `false`.\n */\n function hasUnicodeWord(string) {\n return reHasUnicodeWord.test(string);\n }\n\n /**\n * Converts `iterator` to an array.\n *\n * @private\n * @param {Object} iterator The iterator to convert.\n * @returns {Array} Returns the converted array.\n */\n function iteratorToArray(iterator) {\n var data,\n result = [];\n\n while (!(data = iterator.next()).done) {\n result.push(data.value);\n }\n return result;\n }\n\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 */\n function 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\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 */\n function overArg(func, transform) {\n return function(arg) {\n return func(transform(arg));\n };\n }\n\n /**\n * Replaces all `placeholder` elements in `array` with an internal placeholder\n * and returns an array of their indexes.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {*} placeholder The placeholder to replace.\n * @returns {Array} Returns the new array of placeholder indexes.\n */\n function replaceHolders(array, placeholder) {\n var index = -1,\n length = array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index];\n if (value === placeholder || value === PLACEHOLDER) {\n array[index] = PLACEHOLDER;\n result[resIndex++] = index;\n }\n }\n return result;\n }\n\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 */\n function 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\n /**\n * Converts `set` to its value-value pairs.\n *\n * @private\n * @param {Object} set The set to convert.\n * @returns {Array} Returns the value-value pairs.\n */\n function setToPairs(set) {\n var index = -1,\n result = Array(set.size);\n\n set.forEach(function(value) {\n result[++index] = [value, value];\n });\n return result;\n }\n\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 */\n function 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\n /**\n * A specialized version of `_.lastIndexOf` 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 */\n function strictLastIndexOf(array, value, fromIndex) {\n var index = fromIndex + 1;\n while (index--) {\n if (array[index] === value) {\n return index;\n }\n }\n return index;\n }\n\n /**\n * Gets the number of symbols in `string`.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {number} Returns the string size.\n */\n function stringSize(string) {\n return hasUnicode(string)\n ? unicodeSize(string)\n : asciiSize(string);\n }\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 */\n function stringToArray(string) {\n return hasUnicode(string)\n ? unicodeToArray(string)\n : asciiToArray(string);\n }\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 */\n function trimmedEndIndex(string) {\n var index = string.length;\n\n while (index-- && reWhitespace.test(string.charAt(index))) {}\n return index;\n }\n\n /**\n * Used by `_.unescape` to convert HTML entities to characters.\n *\n * @private\n * @param {string} chr The matched character to unescape.\n * @returns {string} Returns the unescaped character.\n */\n var unescapeHtmlChar = basePropertyOf(htmlUnescapes);\n\n /**\n * Gets the size of a Unicode `string`.\n *\n * @private\n * @param {string} string The string inspect.\n * @returns {number} Returns the string size.\n */\n function unicodeSize(string) {\n var result = reUnicode.lastIndex = 0;\n while (reUnicode.test(string)) {\n ++result;\n }\n return result;\n }\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 */\n function unicodeToArray(string) {\n return string.match(reUnicode) || [];\n }\n\n /**\n * Splits a Unicode `string` into an array of its words.\n *\n * @private\n * @param {string} The string to inspect.\n * @returns {Array} Returns the words of `string`.\n */\n function unicodeWords(string) {\n return string.match(reUnicodeWord) || [];\n }\n\n /*--------------------------------------------------------------------------*/\n\n /**\n * Create a new pristine `lodash` function using the `context` object.\n *\n * @static\n * @memberOf _\n * @since 1.1.0\n * @category Util\n * @param {Object} [context=root] The context object.\n * @returns {Function} Returns a new `lodash` function.\n * @example\n *\n * _.mixin({ 'foo': _.constant('foo') });\n *\n * var lodash = _.runInContext();\n * lodash.mixin({ 'bar': lodash.constant('bar') });\n *\n * _.isFunction(_.foo);\n * // => true\n * _.isFunction(_.bar);\n * // => false\n *\n * lodash.isFunction(lodash.foo);\n * // => false\n * lodash.isFunction(lodash.bar);\n * // => true\n *\n * // Create a suped-up `defer` in Node.js.\n * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer;\n */\n var runInContext = (function runInContext(context) {\n context = context == null ? root : _.defaults(root.Object(), context, _.pick(root, contextProps));\n\n /** Built-in constructor references. */\n var Array = context.Array,\n Date = context.Date,\n Error = context.Error,\n Function = context.Function,\n Math = context.Math,\n Object = context.Object,\n RegExp = context.RegExp,\n String = context.String,\n TypeError = context.TypeError;\n\n /** Used for built-in method references. */\n var arrayProto = Array.prototype,\n funcProto = Function.prototype,\n objectProto = Object.prototype;\n\n /** Used to detect overreaching core-js shims. */\n var coreJsData = context['__core-js_shared__'];\n\n /** Used to resolve the decompiled source of functions. */\n var funcToString = funcProto.toString;\n\n /** Used to check objects for own properties. */\n var hasOwnProperty = objectProto.hasOwnProperty;\n\n /** Used to generate unique IDs. */\n var idCounter = 0;\n\n /** Used to detect methods masquerading as native. */\n var maskSrcKey = (function() {\n var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');\n return uid ? ('Symbol(src)_1.' + uid) : '';\n }());\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 */\n var nativeObjectToString = objectProto.toString;\n\n /** Used to infer the `Object` constructor. */\n var objectCtorString = funcToString.call(Object);\n\n /** Used to restore the original `_` reference in `_.noConflict`. */\n var oldDash = root._;\n\n /** Used to detect if a method is native. */\n var reIsNative = RegExp('^' +\n funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\\\$&')\n .replace(/hasOwnProperty|(function).*?(?=\\\\\\()| for .+?(?=\\\\\\])/g, '$1.*?') + '$'\n );\n\n /** Built-in value references. */\n var Buffer = moduleExports ? context.Buffer : undefined,\n Symbol = context.Symbol,\n Uint8Array = context.Uint8Array,\n allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined,\n getPrototype = overArg(Object.getPrototypeOf, Object),\n objectCreate = Object.create,\n propertyIsEnumerable = objectProto.propertyIsEnumerable,\n splice = arrayProto.splice,\n spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined,\n symIterator = Symbol ? Symbol.iterator : undefined,\n symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n var defineProperty = (function() {\n try {\n var func = getNative(Object, 'defineProperty');\n func({}, '', {});\n return func;\n } catch (e) {}\n }());\n\n /** Mocked built-ins. */\n var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout,\n ctxNow = Date && Date.now !== root.Date.now && Date.now,\n ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout;\n\n /* Built-in method references for those with the same name as other `lodash` methods. */\n var nativeCeil = Math.ceil,\n nativeFloor = Math.floor,\n nativeGetSymbols = Object.getOwnPropertySymbols,\n nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined,\n nativeIsFinite = context.isFinite,\n nativeJoin = arrayProto.join,\n nativeKeys = overArg(Object.keys, Object),\n nativeMax = Math.max,\n nativeMin = Math.min,\n nativeNow = Date.now,\n nativeParseInt = context.parseInt,\n nativeRandom = Math.random,\n nativeReverse = arrayProto.reverse;\n\n /* Built-in method references that are verified to be native. */\n var DataView = getNative(context, 'DataView'),\n Map = getNative(context, 'Map'),\n Promise = getNative(context, 'Promise'),\n Set = getNative(context, 'Set'),\n WeakMap = getNative(context, 'WeakMap'),\n nativeCreate = getNative(Object, 'create');\n\n /** Used to store function metadata. */\n var metaMap = WeakMap && new WeakMap;\n\n /** Used to lookup unminified function names. */\n var realNames = {};\n\n /** Used to detect maps, sets, and weakmaps. */\n var dataViewCtorString = toSource(DataView),\n mapCtorString = toSource(Map),\n promiseCtorString = toSource(Promise),\n setCtorString = toSource(Set),\n weakMapCtorString = toSource(WeakMap);\n\n /** Used to convert symbols to primitives and strings. */\n var symbolProto = Symbol ? Symbol.prototype : undefined,\n symbolValueOf = symbolProto ? symbolProto.valueOf : undefined,\n symbolToString = symbolProto ? symbolProto.toString : undefined;\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates a `lodash` object which wraps `value` to enable implicit method\n * chain sequences. Methods that operate on and return arrays, collections,\n * and functions can be chained together. Methods that retrieve a single value\n * or may return a primitive value will automatically end the chain sequence\n * and return the unwrapped value. Otherwise, the value must be unwrapped\n * with `_#value`.\n *\n * Explicit chain sequences, which must be unwrapped with `_#value`, may be\n * enabled using `_.chain`.\n *\n * The execution of chained methods is lazy, that is, it's deferred until\n * `_#value` is implicitly or explicitly called.\n *\n * Lazy evaluation allows several methods to support shortcut fusion.\n * Shortcut fusion is an optimization to merge iteratee calls; this avoids\n * the creation of intermediate arrays and can greatly reduce the number of\n * iteratee executions. Sections of a chain sequence qualify for shortcut\n * fusion if the section is applied to an array and iteratees accept only\n * one argument. The heuristic for whether a section qualifies for shortcut\n * fusion is subject to change.\n *\n * Chaining is supported in custom builds as long as the `_#value` method is\n * directly or indirectly included in the build.\n *\n * In addition to lodash methods, wrappers have `Array` and `String` methods.\n *\n * The wrapper `Array` methods are:\n * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift`\n *\n * The wrapper `String` methods are:\n * `replace` and `split`\n *\n * The wrapper methods that support shortcut fusion are:\n * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`,\n * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`,\n * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray`\n *\n * The chainable wrapper methods are:\n * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`,\n * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`,\n * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`,\n * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`,\n * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`,\n * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`,\n * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`,\n * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`,\n * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`,\n * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`,\n * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`,\n * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`,\n * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`,\n * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`,\n * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`,\n * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`,\n * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`,\n * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`,\n * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`,\n * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`,\n * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`,\n * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`,\n * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`,\n * `zipObject`, `zipObjectDeep`, and `zipWith`\n *\n * The wrapper methods that are **not** chainable by default are:\n * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`,\n * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`,\n * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`,\n * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`,\n * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`,\n * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`,\n * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`,\n * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`,\n * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`,\n * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`,\n * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`,\n * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`,\n * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`,\n * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`,\n * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`,\n * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`,\n * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`,\n * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`,\n * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`,\n * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`,\n * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`,\n * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`,\n * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`,\n * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`,\n * `upperFirst`, `value`, and `words`\n *\n * @name _\n * @constructor\n * @category Seq\n * @param {*} value The value to wrap in a `lodash` instance.\n * @returns {Object} Returns the new `lodash` wrapper instance.\n * @example\n *\n * function square(n) {\n * return n * n;\n * }\n *\n * var wrapped = _([1, 2, 3]);\n *\n * // Returns an unwrapped value.\n * wrapped.reduce(_.add);\n * // => 6\n *\n * // Returns a wrapped value.\n * var squares = wrapped.map(square);\n *\n * _.isArray(squares);\n * // => false\n *\n * _.isArray(squares.value());\n * // => true\n */\n function lodash(value) {\n if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) {\n if (value instanceof LodashWrapper) {\n return value;\n }\n if (hasOwnProperty.call(value, '__wrapped__')) {\n return wrapperClone(value);\n }\n }\n return new LodashWrapper(value);\n }\n\n /**\n * The base implementation of `_.create` without support for assigning\n * properties to the created object.\n *\n * @private\n * @param {Object} proto The object to inherit from.\n * @returns {Object} Returns the new object.\n */\n var baseCreate = (function() {\n function object() {}\n return function(proto) {\n if (!isObject(proto)) {\n return {};\n }\n if (objectCreate) {\n return objectCreate(proto);\n }\n object.prototype = proto;\n var result = new object;\n object.prototype = undefined;\n return result;\n };\n }());\n\n /**\n * The function whose prototype chain sequence wrappers inherit from.\n *\n * @private\n */\n function baseLodash() {\n // No operation performed.\n }\n\n /**\n * The base constructor for creating `lodash` wrapper objects.\n *\n * @private\n * @param {*} value The value to wrap.\n * @param {boolean} [chainAll] Enable explicit method chain sequences.\n */\n function LodashWrapper(value, chainAll) {\n this.__wrapped__ = value;\n this.__actions__ = [];\n this.__chain__ = !!chainAll;\n this.__index__ = 0;\n this.__values__ = undefined;\n }\n\n /**\n * By default, the template delimiters used by lodash are like those in\n * embedded Ruby (ERB) as well as ES2015 template strings. Change the\n * following template settings to use alternative delimiters.\n *\n * @static\n * @memberOf _\n * @type {Object}\n */\n lodash.templateSettings = {\n\n /**\n * Used to detect `data` property values to be HTML-escaped.\n *\n * @memberOf _.templateSettings\n * @type {RegExp}\n */\n 'escape': reEscape,\n\n /**\n * Used to detect code to be evaluated.\n *\n * @memberOf _.templateSettings\n * @type {RegExp}\n */\n 'evaluate': reEvaluate,\n\n /**\n * Used to detect `data` property values to inject.\n *\n * @memberOf _.templateSettings\n * @type {RegExp}\n */\n 'interpolate': reInterpolate,\n\n /**\n * Used to reference the data object in the template text.\n *\n * @memberOf _.templateSettings\n * @type {string}\n */\n 'variable': '',\n\n /**\n * Used to import variables into the compiled template.\n *\n * @memberOf _.templateSettings\n * @type {Object}\n */\n 'imports': {\n\n /**\n * A reference to the `lodash` function.\n *\n * @memberOf _.templateSettings.imports\n * @type {Function}\n */\n '_': lodash\n }\n };\n\n // Ensure wrappers are instances of `baseLodash`.\n lodash.prototype = baseLodash.prototype;\n lodash.prototype.constructor = lodash;\n\n LodashWrapper.prototype = baseCreate(baseLodash.prototype);\n LodashWrapper.prototype.constructor = LodashWrapper;\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation.\n *\n * @private\n * @constructor\n * @param {*} value The value to wrap.\n */\n function LazyWrapper(value) {\n this.__wrapped__ = value;\n this.__actions__ = [];\n this.__dir__ = 1;\n this.__filtered__ = false;\n this.__iteratees__ = [];\n this.__takeCount__ = MAX_ARRAY_LENGTH;\n this.__views__ = [];\n }\n\n /**\n * Creates a clone of the lazy wrapper object.\n *\n * @private\n * @name clone\n * @memberOf LazyWrapper\n * @returns {Object} Returns the cloned `LazyWrapper` object.\n */\n function lazyClone() {\n var result = new LazyWrapper(this.__wrapped__);\n result.__actions__ = copyArray(this.__actions__);\n result.__dir__ = this.__dir__;\n result.__filtered__ = this.__filtered__;\n result.__iteratees__ = copyArray(this.__iteratees__);\n result.__takeCount__ = this.__takeCount__;\n result.__views__ = copyArray(this.__views__);\n return result;\n }\n\n /**\n * Reverses the direction of lazy iteration.\n *\n * @private\n * @name reverse\n * @memberOf LazyWrapper\n * @returns {Object} Returns the new reversed `LazyWrapper` object.\n */\n function lazyReverse() {\n if (this.__filtered__) {\n var result = new LazyWrapper(this);\n result.__dir__ = -1;\n result.__filtered__ = true;\n } else {\n result = this.clone();\n result.__dir__ *= -1;\n }\n return result;\n }\n\n /**\n * Extracts the unwrapped value from its lazy wrapper.\n *\n * @private\n * @name value\n * @memberOf LazyWrapper\n * @returns {*} Returns the unwrapped value.\n */\n function lazyValue() {\n var array = this.__wrapped__.value(),\n dir = this.__dir__,\n isArr = isArray(array),\n isRight = dir < 0,\n arrLength = isArr ? array.length : 0,\n view = getView(0, arrLength, this.__views__),\n start = view.start,\n end = view.end,\n length = end - start,\n index = isRight ? end : (start - 1),\n iteratees = this.__iteratees__,\n iterLength = iteratees.length,\n resIndex = 0,\n takeCount = nativeMin(length, this.__takeCount__);\n\n if (!isArr || (!isRight && arrLength == length && takeCount == length)) {\n return baseWrapperValue(array, this.__actions__);\n }\n var result = [];\n\n outer:\n while (length-- && resIndex < takeCount) {\n index += dir;\n\n var iterIndex = -1,\n value = array[index];\n\n while (++iterIndex < iterLength) {\n var data = iteratees[iterIndex],\n iteratee = data.iteratee,\n type = data.type,\n computed = iteratee(value);\n\n if (type == LAZY_MAP_FLAG) {\n value = computed;\n } else if (!computed) {\n if (type == LAZY_FILTER_FLAG) {\n continue outer;\n } else {\n break outer;\n }\n }\n }\n result[resIndex++] = value;\n }\n return result;\n }\n\n // Ensure `LazyWrapper` is an instance of `baseLodash`.\n LazyWrapper.prototype = baseCreate(baseLodash.prototype);\n LazyWrapper.prototype.constructor = LazyWrapper;\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates a hash object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\n function 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 /**\n * Removes all key-value entries from the hash.\n *\n * @private\n * @name clear\n * @memberOf Hash\n */\n function hashClear() {\n this.__data__ = nativeCreate ? nativeCreate(null) : {};\n this.size = 0;\n }\n\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 */\n function hashDelete(key) {\n var result = this.has(key) && delete this.__data__[key];\n this.size -= result ? 1 : 0;\n return result;\n }\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 */\n function 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\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 */\n function hashHas(key) {\n var data = this.__data__;\n return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);\n }\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 */\n function 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\n // Add methods to `Hash`.\n Hash.prototype.clear = hashClear;\n Hash.prototype['delete'] = hashDelete;\n Hash.prototype.get = hashGet;\n Hash.prototype.has = hashHas;\n Hash.prototype.set = hashSet;\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates an list cache object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\n function 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 /**\n * Removes all key-value entries from the list cache.\n *\n * @private\n * @name clear\n * @memberOf ListCache\n */\n function listCacheClear() {\n this.__data__ = [];\n this.size = 0;\n }\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 */\n function 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\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 */\n function listCacheGet(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n return index < 0 ? undefined : data[index][1];\n }\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 */\n function listCacheHas(key) {\n return assocIndexOf(this.__data__, key) > -1;\n }\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 */\n function 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\n // Add methods to `ListCache`.\n ListCache.prototype.clear = listCacheClear;\n ListCache.prototype['delete'] = listCacheDelete;\n ListCache.prototype.get = listCacheGet;\n ListCache.prototype.has = listCacheHas;\n ListCache.prototype.set = listCacheSet;\n\n /*------------------------------------------------------------------------*/\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 */\n function 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 /**\n * Removes all key-value entries from the map.\n *\n * @private\n * @name clear\n * @memberOf MapCache\n */\n function mapCacheClear() {\n this.size = 0;\n this.__data__ = {\n 'hash': new Hash,\n 'map': new (Map || ListCache),\n 'string': new Hash\n };\n }\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 */\n function mapCacheDelete(key) {\n var result = getMapData(this, key)['delete'](key);\n this.size -= result ? 1 : 0;\n return result;\n }\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 */\n function mapCacheGet(key) {\n return getMapData(this, key).get(key);\n }\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 */\n function mapCacheHas(key) {\n return getMapData(this, key).has(key);\n }\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 */\n function 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\n // Add methods to `MapCache`.\n MapCache.prototype.clear = mapCacheClear;\n MapCache.prototype['delete'] = mapCacheDelete;\n MapCache.prototype.get = mapCacheGet;\n MapCache.prototype.has = mapCacheHas;\n MapCache.prototype.set = mapCacheSet;\n\n /*------------------------------------------------------------------------*/\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 */\n function 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 /**\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 */\n function setCacheAdd(value) {\n this.__data__.set(value, HASH_UNDEFINED);\n return this;\n }\n\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 */\n function setCacheHas(value) {\n return this.__data__.has(value);\n }\n\n // Add methods to `SetCache`.\n SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;\n SetCache.prototype.has = setCacheHas;\n\n /*------------------------------------------------------------------------*/\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 */\n function Stack(entries) {\n var data = this.__data__ = new ListCache(entries);\n this.size = data.size;\n }\n\n /**\n * Removes all key-value entries from the stack.\n *\n * @private\n * @name clear\n * @memberOf Stack\n */\n function stackClear() {\n this.__data__ = new ListCache;\n this.size = 0;\n }\n\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 */\n function stackDelete(key) {\n var data = this.__data__,\n result = data['delete'](key);\n\n this.size = data.size;\n return result;\n }\n\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 */\n function stackGet(key) {\n return this.__data__.get(key);\n }\n\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 */\n function stackHas(key) {\n return this.__data__.has(key);\n }\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 */\n function 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\n // Add methods to `Stack`.\n Stack.prototype.clear = stackClear;\n Stack.prototype['delete'] = stackDelete;\n Stack.prototype.get = stackGet;\n Stack.prototype.has = stackHas;\n Stack.prototype.set = stackSet;\n\n /*------------------------------------------------------------------------*/\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 */\n function 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\n /**\n * A specialized version of `_.sample` for arrays.\n *\n * @private\n * @param {Array} array The array to sample.\n * @returns {*} Returns the random element.\n */\n function arraySample(array) {\n var length = array.length;\n return length ? array[baseRandom(0, length - 1)] : undefined;\n }\n\n /**\n * A specialized version of `_.sampleSize` for arrays.\n *\n * @private\n * @param {Array} array The array to sample.\n * @param {number} n The number of elements to sample.\n * @returns {Array} Returns the random elements.\n */\n function arraySampleSize(array, n) {\n return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length));\n }\n\n /**\n * A specialized version of `_.shuffle` for arrays.\n *\n * @private\n * @param {Array} array The array to shuffle.\n * @returns {Array} Returns the new shuffled array.\n */\n function arrayShuffle(array) {\n return shuffleSelf(copyArray(array));\n }\n\n /**\n * This function is like `assignValue` except that it doesn't assign\n * `undefined` values.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\n function assignMergeValue(object, key, value) {\n if ((value !== undefined && !eq(object[key], value)) ||\n (value === undefined && !(key in object))) {\n baseAssignValue(object, key, value);\n }\n }\n\n /**\n * Assigns `value` to `key` of `object` if the existing value is not equivalent\n * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\n function assignValue(object, key, value) {\n var objValue = object[key];\n if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||\n (value === undefined && !(key in object))) {\n baseAssignValue(object, key, value);\n }\n }\n\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 */\n function 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\n /**\n * Aggregates elements of `collection` on `accumulator` with keys transformed\n * by `iteratee` and values set by `setter`.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} setter The function to set `accumulator` values.\n * @param {Function} iteratee The iteratee to transform keys.\n * @param {Object} accumulator The initial aggregated object.\n * @returns {Function} Returns `accumulator`.\n */\n function baseAggregator(collection, setter, iteratee, accumulator) {\n baseEach(collection, function(value, key, collection) {\n setter(accumulator, value, iteratee(value), collection);\n });\n return accumulator;\n }\n\n /**\n * The base implementation of `_.assign` without support for multiple sources\n * or `customizer` functions.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @returns {Object} Returns `object`.\n */\n function baseAssign(object, source) {\n return object && copyObject(source, keys(source), object);\n }\n\n /**\n * The base implementation of `_.assignIn` without support for multiple sources\n * or `customizer` functions.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @returns {Object} Returns `object`.\n */\n function baseAssignIn(object, source) {\n return object && copyObject(source, keysIn(source), object);\n }\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 */\n function 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\n /**\n * The base implementation of `_.at` without support for individual paths.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {string[]} paths The property paths to pick.\n * @returns {Array} Returns the picked elements.\n */\n function baseAt(object, paths) {\n var index = -1,\n length = paths.length,\n result = Array(length),\n skip = object == null;\n\n while (++index < length) {\n result[index] = skip ? undefined : get(object, paths[index]);\n }\n return result;\n }\n\n /**\n * The base implementation of `_.clamp` which doesn't coerce arguments.\n *\n * @private\n * @param {number} number The number to clamp.\n * @param {number} [lower] The lower bound.\n * @param {number} upper The upper bound.\n * @returns {number} Returns the clamped number.\n */\n function baseClamp(number, lower, upper) {\n if (number === number) {\n if (upper !== undefined) {\n number = number <= upper ? number : upper;\n }\n if (lower !== undefined) {\n number = number >= lower ? number : lower;\n }\n }\n return number;\n }\n\n /**\n * The base implementation of `_.clone` and `_.cloneDeep` which tracks\n * traversed objects.\n *\n * @private\n * @param {*} value The value to clone.\n * @param {boolean} bitmask The bitmask flags.\n * 1 - Deep clone\n * 2 - Flatten inherited properties\n * 4 - Clone symbols\n * @param {Function} [customizer] The function to customize cloning.\n * @param {string} [key] The key of `value`.\n * @param {Object} [object] The parent object of `value`.\n * @param {Object} [stack] Tracks traversed objects and their clone counterparts.\n * @returns {*} Returns the cloned value.\n */\n function baseClone(value, bitmask, customizer, key, object, stack) {\n var result,\n isDeep = bitmask & CLONE_DEEP_FLAG,\n isFlat = bitmask & CLONE_FLAT_FLAG,\n isFull = bitmask & CLONE_SYMBOLS_FLAG;\n\n if (customizer) {\n result = object ? customizer(value, key, object, stack) : customizer(value);\n }\n if (result !== undefined) {\n return result;\n }\n if (!isObject(value)) {\n return value;\n }\n var isArr = isArray(value);\n if (isArr) {\n result = initCloneArray(value);\n if (!isDeep) {\n return copyArray(value, result);\n }\n } else {\n var tag = getTag(value),\n isFunc = tag == funcTag || tag == genTag;\n\n if (isBuffer(value)) {\n return cloneBuffer(value, isDeep);\n }\n if (tag == objectTag || tag == argsTag || (isFunc && !object)) {\n result = (isFlat || isFunc) ? {} : initCloneObject(value);\n if (!isDeep) {\n return isFlat\n ? copySymbolsIn(value, baseAssignIn(result, value))\n : copySymbols(value, baseAssign(result, value));\n }\n } else {\n if (!cloneableTags[tag]) {\n return object ? value : {};\n }\n result = initCloneByTag(value, tag, isDeep);\n }\n }\n // Check for circular references and return its corresponding clone.\n stack || (stack = new Stack);\n var stacked = stack.get(value);\n if (stacked) {\n return stacked;\n }\n stack.set(value, result);\n\n if (isSet(value)) {\n value.forEach(function(subValue) {\n result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));\n });\n } else if (isMap(value)) {\n value.forEach(function(subValue, key) {\n result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack));\n });\n }\n\n var keysFunc = isFull\n ? (isFlat ? getAllKeysIn : getAllKeys)\n : (isFlat ? keysIn : keys);\n\n var props = isArr ? undefined : keysFunc(value);\n arrayEach(props || value, function(subValue, key) {\n if (props) {\n key = subValue;\n subValue = value[key];\n }\n // Recursively populate clone (susceptible to call stack limits).\n assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack));\n });\n return result;\n }\n\n /**\n * The base implementation of `_.conforms` which doesn't clone `source`.\n *\n * @private\n * @param {Object} source The object of property predicates to conform to.\n * @returns {Function} Returns the new spec function.\n */\n function baseConforms(source) {\n var props = keys(source);\n return function(object) {\n return baseConformsTo(object, source, props);\n };\n }\n\n /**\n * The base implementation of `_.conformsTo` which accepts `props` to check.\n *\n * @private\n * @param {Object} object The object to inspect.\n * @param {Object} source The object of property predicates to conform to.\n * @returns {boolean} Returns `true` if `object` conforms, else `false`.\n */\n function baseConformsTo(object, source, props) {\n var length = props.length;\n if (object == null) {\n return !length;\n }\n object = Object(object);\n while (length--) {\n var key = props[length],\n predicate = source[key],\n value = object[key];\n\n if ((value === undefined && !(key in object)) || !predicate(value)) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * The base implementation of `_.delay` and `_.defer` which accepts `args`\n * to provide to `func`.\n *\n * @private\n * @param {Function} func The function to delay.\n * @param {number} wait The number of milliseconds to delay invocation.\n * @param {Array} args The arguments to provide to `func`.\n * @returns {number|Object} Returns the timer id or timeout object.\n */\n function baseDelay(func, wait, args) {\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n return setTimeout(function() { func.apply(undefined, args); }, wait);\n }\n\n /**\n * The base implementation of methods like `_.difference` without support\n * for excluding multiple arrays or iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Array} values The values to exclude.\n * @param {Function} [iteratee] The iteratee invoked per element.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new array of filtered values.\n */\n function baseDifference(array, values, iteratee, comparator) {\n var index = -1,\n includes = arrayIncludes,\n isCommon = true,\n length = array.length,\n result = [],\n valuesLength = values.length;\n\n if (!length) {\n return result;\n }\n if (iteratee) {\n values = arrayMap(values, baseUnary(iteratee));\n }\n if (comparator) {\n includes = arrayIncludesWith;\n isCommon = false;\n }\n else if (values.length >= LARGE_ARRAY_SIZE) {\n includes = cacheHas;\n isCommon = false;\n values = new SetCache(values);\n }\n outer:\n while (++index < length) {\n var value = array[index],\n computed = iteratee == null ? value : iteratee(value);\n\n value = (comparator || value !== 0) ? value : 0;\n if (isCommon && computed === computed) {\n var valuesIndex = valuesLength;\n while (valuesIndex--) {\n if (values[valuesIndex] === computed) {\n continue outer;\n }\n }\n result.push(value);\n }\n else if (!includes(values, computed, comparator)) {\n result.push(value);\n }\n }\n return result;\n }\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 */\n var baseEach = createBaseEach(baseForOwn);\n\n /**\n * The base implementation of `_.forEachRight` 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 */\n var baseEachRight = createBaseEach(baseForOwnRight, true);\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 */\n function 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\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 */\n function 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\n /**\n * The base implementation of `_.fill` without an iteratee call guard.\n *\n * @private\n * @param {Array} array The array to fill.\n * @param {*} value The value to fill `array` with.\n * @param {number} [start=0] The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns `array`.\n */\n function baseFill(array, value, start, end) {\n var length = array.length;\n\n start = toInteger(start);\n if (start < 0) {\n start = -start > length ? 0 : (length + start);\n }\n end = (end === undefined || end > length) ? length : toInteger(end);\n if (end < 0) {\n end += length;\n }\n end = start > end ? 0 : toLength(end);\n while (start < end) {\n array[start++] = value;\n }\n return array;\n }\n\n /**\n * The base implementation of `_.filter` 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 {Array} Returns the new filtered array.\n */\n function baseFilter(collection, predicate) {\n var result = [];\n baseEach(collection, function(value, index, collection) {\n if (predicate(value, index, collection)) {\n result.push(value);\n }\n });\n return result;\n }\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 */\n function 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\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 */\n var baseFor = createBaseFor();\n\n /**\n * This function is like `baseFor` except that it iterates over properties\n * in the opposite order.\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 */\n var baseForRight = createBaseFor(true);\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 */\n function baseForOwn(object, iteratee) {\n return object && baseFor(object, iteratee, keys);\n }\n\n /**\n * The base implementation of `_.forOwnRight` 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 */\n function baseForOwnRight(object, iteratee) {\n return object && baseForRight(object, iteratee, keys);\n }\n\n /**\n * The base implementation of `_.functions` which creates an array of\n * `object` function property names filtered from `props`.\n *\n * @private\n * @param {Object} object The object to inspect.\n * @param {Array} props The property names to filter.\n * @returns {Array} Returns the function names.\n */\n function baseFunctions(object, props) {\n return arrayFilter(props, function(key) {\n return isFunction(object[key]);\n });\n }\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 */\n function 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\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 */\n function baseGetAllKeys(object, keysFunc, symbolsFunc) {\n var result = keysFunc(object);\n return isArray(object) ? result : arrayPush(result, symbolsFunc(object));\n }\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 */\n function 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\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 */\n function baseGt(value, other) {\n return value > other;\n }\n\n /**\n * The base implementation of `_.has` 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 */\n function baseHas(object, key) {\n return object != null && hasOwnProperty.call(object, key);\n }\n\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 */\n function baseHasIn(object, key) {\n return object != null && key in Object(object);\n }\n\n /**\n * The base implementation of `_.inRange` which doesn't coerce arguments.\n *\n * @private\n * @param {number} number The number to check.\n * @param {number} start The start of the range.\n * @param {number} end The end of the range.\n * @returns {boolean} Returns `true` if `number` is in the range, else `false`.\n */\n function baseInRange(number, start, end) {\n return number >= nativeMin(start, end) && number < nativeMax(start, end);\n }\n\n /**\n * The base implementation of methods like `_.intersection`, without support\n * for iteratee shorthands, that accepts an array of arrays to inspect.\n *\n * @private\n * @param {Array} arrays The arrays 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 array of shared values.\n */\n function baseIntersection(arrays, iteratee, comparator) {\n var includes = comparator ? arrayIncludesWith : arrayIncludes,\n length = arrays[0].length,\n othLength = arrays.length,\n othIndex = othLength,\n caches = Array(othLength),\n maxLength = Infinity,\n result = [];\n\n while (othIndex--) {\n var array = arrays[othIndex];\n if (othIndex && iteratee) {\n array = arrayMap(array, baseUnary(iteratee));\n }\n maxLength = nativeMin(array.length, maxLength);\n caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120))\n ? new SetCache(othIndex && array)\n : undefined;\n }\n array = arrays[0];\n\n var index = -1,\n seen = caches[0];\n\n outer:\n while (++index < length && result.length < maxLength) {\n var value = array[index],\n computed = iteratee ? iteratee(value) : value;\n\n value = (comparator || value !== 0) ? value : 0;\n if (!(seen\n ? cacheHas(seen, computed)\n : includes(result, computed, comparator)\n )) {\n othIndex = othLength;\n while (--othIndex) {\n var cache = caches[othIndex];\n if (!(cache\n ? cacheHas(cache, computed)\n : includes(arrays[othIndex], computed, comparator))\n ) {\n continue outer;\n }\n }\n if (seen) {\n seen.push(computed);\n }\n result.push(value);\n }\n }\n return result;\n }\n\n /**\n * The base implementation of `_.invert` and `_.invertBy` which inverts\n * `object` with values transformed by `iteratee` and set by `setter`.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {Function} setter The function to set `accumulator` values.\n * @param {Function} iteratee The iteratee to transform values.\n * @param {Object} accumulator The initial inverted object.\n * @returns {Function} Returns `accumulator`.\n */\n function baseInverter(object, setter, iteratee, accumulator) {\n baseForOwn(object, function(value, key, object) {\n setter(accumulator, iteratee(value), key, object);\n });\n return accumulator;\n }\n\n /**\n * The base implementation of `_.invoke` without support for individual\n * method arguments.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array|string} path The path of the method to invoke.\n * @param {Array} args The arguments to invoke the method with.\n * @returns {*} Returns the result of the invoked method.\n */\n function baseInvoke(object, path, args) {\n path = castPath(path, object);\n object = parent(object, path);\n var func = object == null ? object : object[toKey(last(path))];\n return func == null ? undefined : apply(func, object, args);\n }\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 */\n function baseIsArguments(value) {\n return isObjectLike(value) && baseGetTag(value) == argsTag;\n }\n\n /**\n * The base implementation of `_.isArrayBuffer` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`.\n */\n function baseIsArrayBuffer(value) {\n return isObjectLike(value) && baseGetTag(value) == arrayBufferTag;\n }\n\n /**\n * The base implementation of `_.isDate` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a date object, else `false`.\n */\n function baseIsDate(value) {\n return isObjectLike(value) && baseGetTag(value) == dateTag;\n }\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 */\n function 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\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 */\n function 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\n /**\n * The base implementation of `_.isMap` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a map, else `false`.\n */\n function baseIsMap(value) {\n return isObjectLike(value) && getTag(value) == mapTag;\n }\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 */\n function 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\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 */\n function 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\n /**\n * The base implementation of `_.isRegExp` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a regexp, else `false`.\n */\n function baseIsRegExp(value) {\n return isObjectLike(value) && baseGetTag(value) == regexpTag;\n }\n\n /**\n * The base implementation of `_.isSet` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a set, else `false`.\n */\n function baseIsSet(value) {\n return isObjectLike(value) && getTag(value) == setTag;\n }\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 */\n function baseIsTypedArray(value) {\n return isObjectLike(value) &&\n isLength(value.length) && !!typedArrayTags[baseGetTag(value)];\n }\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 */\n function 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\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 */\n function 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\n /**\n * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\n function baseKeysIn(object) {\n if (!isObject(object)) {\n return nativeKeysIn(object);\n }\n var isProto = isPrototype(object),\n result = [];\n\n for (var key in object) {\n if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {\n result.push(key);\n }\n }\n return result;\n }\n\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 */\n function baseLt(value, other) {\n return value < other;\n }\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 */\n function 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\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 */\n function 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\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 */\n function 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\n /**\n * The base implementation of `_.merge` without support for multiple sources.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @param {number} srcIndex The index of `source`.\n * @param {Function} [customizer] The function to customize merged values.\n * @param {Object} [stack] Tracks traversed source values and their merged\n * counterparts.\n */\n function baseMerge(object, source, srcIndex, customizer, stack) {\n if (object === source) {\n return;\n }\n baseFor(source, function(srcValue, key) {\n stack || (stack = new Stack);\n if (isObject(srcValue)) {\n baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack);\n }\n else {\n var newValue = customizer\n ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack)\n : undefined;\n\n if (newValue === undefined) {\n newValue = srcValue;\n }\n assignMergeValue(object, key, newValue);\n }\n }, keysIn);\n }\n\n /**\n * A specialized version of `baseMerge` for arrays and objects which performs\n * deep merges and tracks traversed objects enabling objects with circular\n * references to be merged.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @param {string} key The key of the value to merge.\n * @param {number} srcIndex The index of `source`.\n * @param {Function} mergeFunc The function to merge values.\n * @param {Function} [customizer] The function to customize assigned values.\n * @param {Object} [stack] Tracks traversed source values and their merged\n * counterparts.\n */\n function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) {\n var objValue = safeGet(object, key),\n srcValue = safeGet(source, key),\n stacked = stack.get(srcValue);\n\n if (stacked) {\n assignMergeValue(object, key, stacked);\n return;\n }\n var newValue = customizer\n ? customizer(objValue, srcValue, (key + ''), object, source, stack)\n : undefined;\n\n var isCommon = newValue === undefined;\n\n if (isCommon) {\n var isArr = isArray(srcValue),\n isBuff = !isArr && isBuffer(srcValue),\n isTyped = !isArr && !isBuff && isTypedArray(srcValue);\n\n newValue = srcValue;\n if (isArr || isBuff || isTyped) {\n if (isArray(objValue)) {\n newValue = objValue;\n }\n else if (isArrayLikeObject(objValue)) {\n newValue = copyArray(objValue);\n }\n else if (isBuff) {\n isCommon = false;\n newValue = cloneBuffer(srcValue, true);\n }\n else if (isTyped) {\n isCommon = false;\n newValue = cloneTypedArray(srcValue, true);\n }\n else {\n newValue = [];\n }\n }\n else if (isPlainObject(srcValue) || isArguments(srcValue)) {\n newValue = objValue;\n if (isArguments(objValue)) {\n newValue = toPlainObject(objValue);\n }\n else if (!isObject(objValue) || isFunction(objValue)) {\n newValue = initCloneObject(srcValue);\n }\n }\n else {\n isCommon = false;\n }\n }\n if (isCommon) {\n // Recursively merge objects and arrays (susceptible to call stack limits).\n stack.set(srcValue, newValue);\n mergeFunc(newValue, srcValue, srcIndex, customizer, stack);\n stack['delete'](srcValue);\n }\n assignMergeValue(object, key, newValue);\n }\n\n /**\n * The base implementation of `_.nth` which doesn't coerce arguments.\n *\n * @private\n * @param {Array} array The array to query.\n * @param {number} n The index of the element to return.\n * @returns {*} Returns the nth element of `array`.\n */\n function baseNth(array, n) {\n var length = array.length;\n if (!length) {\n return;\n }\n n += n < 0 ? length : 0;\n return isIndex(n, length) ? array[n] : undefined;\n }\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 */\n function 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(getIteratee()));\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\n /**\n * The base implementation of `_.pick` without support for individual\n * property identifiers.\n *\n * @private\n * @param {Object} object The source object.\n * @param {string[]} paths The property paths to pick.\n * @returns {Object} Returns the new object.\n */\n function basePick(object, paths) {\n return basePickBy(object, paths, function(value, path) {\n return hasIn(object, path);\n });\n }\n\n /**\n * The base implementation of `_.pickBy` without support for iteratee shorthands.\n *\n * @private\n * @param {Object} object The source object.\n * @param {string[]} paths The property paths to pick.\n * @param {Function} predicate The function invoked per property.\n * @returns {Object} Returns the new object.\n */\n function basePickBy(object, paths, predicate) {\n var index = -1,\n length = paths.length,\n result = {};\n\n while (++index < length) {\n var path = paths[index],\n value = baseGet(object, path);\n\n if (predicate(value, path)) {\n baseSet(result, castPath(path, object), value);\n }\n }\n return result;\n }\n\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 */\n function basePropertyDeep(path) {\n return function(object) {\n return baseGet(object, path);\n };\n }\n\n /**\n * The base implementation of `_.pullAllBy` without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {Array} values The values to remove.\n * @param {Function} [iteratee] The iteratee invoked per element.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns `array`.\n */\n function basePullAll(array, values, iteratee, comparator) {\n var indexOf = comparator ? baseIndexOfWith : baseIndexOf,\n index = -1,\n length = values.length,\n seen = array;\n\n if (array === values) {\n values = copyArray(values);\n }\n if (iteratee) {\n seen = arrayMap(array, baseUnary(iteratee));\n }\n while (++index < length) {\n var fromIndex = 0,\n value = values[index],\n computed = iteratee ? iteratee(value) : value;\n\n while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) {\n if (seen !== array) {\n splice.call(seen, fromIndex, 1);\n }\n splice.call(array, fromIndex, 1);\n }\n }\n return array;\n }\n\n /**\n * The base implementation of `_.pullAt` without support for individual\n * indexes or capturing the removed elements.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {number[]} indexes The indexes of elements to remove.\n * @returns {Array} Returns `array`.\n */\n function basePullAt(array, indexes) {\n var length = array ? indexes.length : 0,\n lastIndex = length - 1;\n\n while (length--) {\n var index = indexes[length];\n if (length == lastIndex || index !== previous) {\n var previous = index;\n if (isIndex(index)) {\n splice.call(array, index, 1);\n } else {\n baseUnset(array, index);\n }\n }\n }\n return array;\n }\n\n /**\n * The base implementation of `_.random` without support for returning\n * floating-point numbers.\n *\n * @private\n * @param {number} lower The lower bound.\n * @param {number} upper The upper bound.\n * @returns {number} Returns the random number.\n */\n function baseRandom(lower, upper) {\n return lower + nativeFloor(nativeRandom() * (upper - lower + 1));\n }\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 */\n function 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\n /**\n * The base implementation of `_.repeat` which doesn't coerce arguments.\n *\n * @private\n * @param {string} string The string to repeat.\n * @param {number} n The number of times to repeat the string.\n * @returns {string} Returns the repeated string.\n */\n function baseRepeat(string, n) {\n var result = '';\n if (!string || n < 1 || n > MAX_SAFE_INTEGER) {\n return result;\n }\n // Leverage the exponentiation by squaring algorithm for a faster repeat.\n // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details.\n do {\n if (n % 2) {\n result += string;\n }\n n = nativeFloor(n / 2);\n if (n) {\n string += string;\n }\n } while (n);\n\n return result;\n }\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 */\n function baseRest(func, start) {\n return setToString(overRest(func, start, identity), func + '');\n }\n\n /**\n * The base implementation of `_.sample`.\n *\n * @private\n * @param {Array|Object} collection The collection to sample.\n * @returns {*} Returns the random element.\n */\n function baseSample(collection) {\n return arraySample(values(collection));\n }\n\n /**\n * The base implementation of `_.sampleSize` without param guards.\n *\n * @private\n * @param {Array|Object} collection The collection to sample.\n * @param {number} n The number of elements to sample.\n * @returns {Array} Returns the random elements.\n */\n function baseSampleSize(collection, n) {\n var array = values(collection);\n return shuffleSelf(array, baseClamp(n, 0, array.length));\n }\n\n /**\n * The base implementation of `_.set`.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {Array|string} path The path of the property to set.\n * @param {*} value The value to set.\n * @param {Function} [customizer] The function to customize path creation.\n * @returns {Object} Returns `object`.\n */\n function baseSet(object, path, value, customizer) {\n if (!isObject(object)) {\n return object;\n }\n path = castPath(path, object);\n\n var index = -1,\n length = path.length,\n lastIndex = length - 1,\n nested = object;\n\n while (nested != null && ++index < length) {\n var key = toKey(path[index]),\n newValue = value;\n\n if (key === '__proto__' || key === 'constructor' || key === 'prototype') {\n return object;\n }\n\n if (index != lastIndex) {\n var objValue = nested[key];\n newValue = customizer ? customizer(objValue, key, nested) : undefined;\n if (newValue === undefined) {\n newValue = isObject(objValue)\n ? objValue\n : (isIndex(path[index + 1]) ? [] : {});\n }\n }\n assignValue(nested, key, newValue);\n nested = nested[key];\n }\n return object;\n }\n\n /**\n * The base implementation of `setData` without support for hot loop shorting.\n *\n * @private\n * @param {Function} func The function to associate metadata with.\n * @param {*} data The metadata.\n * @returns {Function} Returns `func`.\n */\n var baseSetData = !metaMap ? identity : function(func, data) {\n metaMap.set(func, data);\n return func;\n };\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 */\n var 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\n /**\n * The base implementation of `_.shuffle`.\n *\n * @private\n * @param {Array|Object} collection The collection to shuffle.\n * @returns {Array} Returns the new shuffled array.\n */\n function baseShuffle(collection) {\n return shuffleSelf(values(collection));\n }\n\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 */\n function 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\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 */\n function 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\n /**\n * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which\n * performs a binary search of `array` to determine the index at which `value`\n * should be inserted into `array` in order to maintain its sort order.\n *\n * @private\n * @param {Array} array The sorted array to inspect.\n * @param {*} value The value to evaluate.\n * @param {boolean} [retHighest] Specify returning the highest qualified index.\n * @returns {number} Returns the index at which `value` should be inserted\n * into `array`.\n */\n function baseSortedIndex(array, value, retHighest) {\n var low = 0,\n high = array == null ? low : array.length;\n\n if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) {\n while (low < high) {\n var mid = (low + high) >>> 1,\n computed = array[mid];\n\n if (computed !== null && !isSymbol(computed) &&\n (retHighest ? (computed <= value) : (computed < value))) {\n low = mid + 1;\n } else {\n high = mid;\n }\n }\n return high;\n }\n return baseSortedIndexBy(array, value, identity, retHighest);\n }\n\n /**\n * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy`\n * which invokes `iteratee` for `value` and each element of `array` to compute\n * their sort ranking. The iteratee is invoked with one argument; (value).\n *\n * @private\n * @param {Array} array The sorted array to inspect.\n * @param {*} value The value to evaluate.\n * @param {Function} iteratee The iteratee invoked per element.\n * @param {boolean} [retHighest] Specify returning the highest qualified index.\n * @returns {number} Returns the index at which `value` should be inserted\n * into `array`.\n */\n function baseSortedIndexBy(array, value, iteratee, retHighest) {\n var low = 0,\n high = array == null ? 0 : array.length;\n if (high === 0) {\n return 0;\n }\n\n value = iteratee(value);\n var valIsNaN = value !== value,\n valIsNull = value === null,\n valIsSymbol = isSymbol(value),\n valIsUndefined = value === undefined;\n\n while (low < high) {\n var mid = nativeFloor((low + high) / 2),\n computed = iteratee(array[mid]),\n othIsDefined = computed !== undefined,\n othIsNull = computed === null,\n othIsReflexive = computed === computed,\n othIsSymbol = isSymbol(computed);\n\n if (valIsNaN) {\n var setLow = retHighest || othIsReflexive;\n } else if (valIsUndefined) {\n setLow = othIsReflexive && (retHighest || othIsDefined);\n } else if (valIsNull) {\n setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull);\n } else if (valIsSymbol) {\n setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol);\n } else if (othIsNull || othIsSymbol) {\n setLow = false;\n } else {\n setLow = retHighest ? (computed <= value) : (computed < value);\n }\n if (setLow) {\n low = mid + 1;\n } else {\n high = mid;\n }\n }\n return nativeMin(high, MAX_ARRAY_INDEX);\n }\n\n /**\n * The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without\n * 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 * @returns {Array} Returns the new duplicate free array.\n */\n function baseSortedUniq(array, iteratee) {\n var index = -1,\n length = array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index],\n computed = iteratee ? iteratee(value) : value;\n\n if (!index || !eq(computed, seen)) {\n var seen = computed;\n result[resIndex++] = value === 0 ? 0 : value;\n }\n }\n return result;\n }\n\n /**\n * The base implementation of `_.toNumber` which doesn't ensure correct\n * conversions of binary, hexadecimal, or octal string values.\n *\n * @private\n * @param {*} value The value to process.\n * @returns {number} Returns the number.\n */\n function baseToNumber(value) {\n if (typeof value == 'number') {\n return value;\n }\n if (isSymbol(value)) {\n return NAN;\n }\n return +value;\n }\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 */\n function 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\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 */\n function 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\n /**\n * The base implementation of `_.unset`.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {Array|string} path The property path to unset.\n * @returns {boolean} Returns `true` if the property is deleted, else `false`.\n */\n function baseUnset(object, path) {\n path = castPath(path, object);\n object = parent(object, path);\n return object == null || delete object[toKey(last(path))];\n }\n\n /**\n * The base implementation of `_.update`.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {Array|string} path The path of the property to update.\n * @param {Function} updater The function to produce the updated value.\n * @param {Function} [customizer] The function to customize path creation.\n * @returns {Object} Returns `object`.\n */\n function baseUpdate(object, path, updater, customizer) {\n return baseSet(object, path, updater(baseGet(object, path)), customizer);\n }\n\n /**\n * The base implementation of methods like `_.dropWhile` and `_.takeWhile`\n * without support for iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to query.\n * @param {Function} predicate The function invoked per iteration.\n * @param {boolean} [isDrop] Specify dropping elements instead of taking them.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Array} Returns the slice of `array`.\n */\n function baseWhile(array, predicate, isDrop, fromRight) {\n var length = array.length,\n index = fromRight ? length : -1;\n\n while ((fromRight ? index-- : ++index < length) &&\n predicate(array[index], index, array)) {}\n\n return isDrop\n ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length))\n : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index));\n }\n\n /**\n * The base implementation of `wrapperValue` which returns the result of\n * performing a sequence of actions on the unwrapped `value`, where each\n * successive action is supplied the return value of the previous.\n *\n * @private\n * @param {*} value The unwrapped value.\n * @param {Array} actions Actions to perform to resolve the unwrapped value.\n * @returns {*} Returns the resolved value.\n */\n function baseWrapperValue(value, actions) {\n var result = value;\n if (result instanceof LazyWrapper) {\n result = result.value();\n }\n return arrayReduce(actions, function(result, action) {\n return action.func.apply(action.thisArg, arrayPush([result], action.args));\n }, result);\n }\n\n /**\n * The base implementation of methods like `_.xor`, without support for\n * iteratee shorthands, that accepts an array of arrays to inspect.\n *\n * @private\n * @param {Array} arrays The arrays 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 array of values.\n */\n function baseXor(arrays, iteratee, comparator) {\n var length = arrays.length;\n if (length < 2) {\n return length ? baseUniq(arrays[0]) : [];\n }\n var index = -1,\n result = Array(length);\n\n while (++index < length) {\n var array = arrays[index],\n othIndex = -1;\n\n while (++othIndex < length) {\n if (othIndex != index) {\n result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator);\n }\n }\n }\n return baseUniq(baseFlatten(result, 1), iteratee, comparator);\n }\n\n /**\n * This base implementation of `_.zipObject` which assigns values using `assignFunc`.\n *\n * @private\n * @param {Array} props The property identifiers.\n * @param {Array} values The property values.\n * @param {Function} assignFunc The function to assign values.\n * @returns {Object} Returns the new object.\n */\n function baseZipObject(props, values, assignFunc) {\n var index = -1,\n length = props.length,\n valsLength = values.length,\n result = {};\n\n while (++index < length) {\n var value = index < valsLength ? values[index] : undefined;\n assignFunc(result, props[index], value);\n }\n return result;\n }\n\n /**\n * Casts `value` to an empty array if it's not an array like object.\n *\n * @private\n * @param {*} value The value to inspect.\n * @returns {Array|Object} Returns the cast array-like object.\n */\n function castArrayLikeObject(value) {\n return isArrayLikeObject(value) ? value : [];\n }\n\n /**\n * Casts `value` to `identity` if it's not a function.\n *\n * @private\n * @param {*} value The value to inspect.\n * @returns {Function} Returns cast function.\n */\n function castFunction(value) {\n return typeof value == 'function' ? value : identity;\n }\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 */\n function castPath(value, object) {\n if (isArray(value)) {\n return value;\n }\n return isKey(value, object) ? [value] : stringToPath(toString(value));\n }\n\n /**\n * A `baseRest` alias which can be replaced with `identity` by module\n * replacement plugins.\n *\n * @private\n * @type {Function}\n * @param {Function} func The function to apply a rest parameter to.\n * @returns {Function} Returns the new function.\n */\n var castRest = baseRest;\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 */\n function 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\n /**\n * A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout).\n *\n * @private\n * @param {number|Object} id The timer id or timeout object of the timer to clear.\n */\n var clearTimeout = ctxClearTimeout || function(id) {\n return root.clearTimeout(id);\n };\n\n /**\n * Creates a clone of `buffer`.\n *\n * @private\n * @param {Buffer} buffer The buffer to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Buffer} Returns the cloned buffer.\n */\n function cloneBuffer(buffer, isDeep) {\n if (isDeep) {\n return buffer.slice();\n }\n var length = buffer.length,\n result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);\n\n buffer.copy(result);\n return result;\n }\n\n /**\n * Creates a clone of `arrayBuffer`.\n *\n * @private\n * @param {ArrayBuffer} arrayBuffer The array buffer to clone.\n * @returns {ArrayBuffer} Returns the cloned array buffer.\n */\n function cloneArrayBuffer(arrayBuffer) {\n var result = new arrayBuffer.constructor(arrayBuffer.byteLength);\n new Uint8Array(result).set(new Uint8Array(arrayBuffer));\n return result;\n }\n\n /**\n * Creates a clone of `dataView`.\n *\n * @private\n * @param {Object} dataView The data view to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the cloned data view.\n */\n function cloneDataView(dataView, isDeep) {\n var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer;\n return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);\n }\n\n /**\n * Creates a clone of `regexp`.\n *\n * @private\n * @param {Object} regexp The regexp to clone.\n * @returns {Object} Returns the cloned regexp.\n */\n function cloneRegExp(regexp) {\n var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));\n result.lastIndex = regexp.lastIndex;\n return result;\n }\n\n /**\n * Creates a clone of the `symbol` object.\n *\n * @private\n * @param {Object} symbol The symbol object to clone.\n * @returns {Object} Returns the cloned symbol object.\n */\n function cloneSymbol(symbol) {\n return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};\n }\n\n /**\n * Creates a clone of `typedArray`.\n *\n * @private\n * @param {Object} typedArray The typed array to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the cloned typed array.\n */\n function cloneTypedArray(typedArray, isDeep) {\n var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;\n return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);\n }\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 */\n function 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\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 */\n function 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\n /**\n * Creates an array that is the composition of partially applied arguments,\n * placeholders, and provided arguments into a single array of arguments.\n *\n * @private\n * @param {Array} args The provided arguments.\n * @param {Array} partials The arguments to prepend to those provided.\n * @param {Array} holders The `partials` placeholder indexes.\n * @params {boolean} [isCurried] Specify composing for a curried function.\n * @returns {Array} Returns the new array of composed arguments.\n */\n function composeArgs(args, partials, holders, isCurried) {\n var argsIndex = -1,\n argsLength = args.length,\n holdersLength = holders.length,\n leftIndex = -1,\n leftLength = partials.length,\n rangeLength = nativeMax(argsLength - holdersLength, 0),\n result = Array(leftLength + rangeLength),\n isUncurried = !isCurried;\n\n while (++leftIndex < leftLength) {\n result[leftIndex] = partials[leftIndex];\n }\n while (++argsIndex < holdersLength) {\n if (isUncurried || argsIndex < argsLength) {\n result[holders[argsIndex]] = args[argsIndex];\n }\n }\n while (rangeLength--) {\n result[leftIndex++] = args[argsIndex++];\n }\n return result;\n }\n\n /**\n * This function is like `composeArgs` except that the arguments composition\n * is tailored for `_.partialRight`.\n *\n * @private\n * @param {Array} args The provided arguments.\n * @param {Array} partials The arguments to append to those provided.\n * @param {Array} holders The `partials` placeholder indexes.\n * @params {boolean} [isCurried] Specify composing for a curried function.\n * @returns {Array} Returns the new array of composed arguments.\n */\n function composeArgsRight(args, partials, holders, isCurried) {\n var argsIndex = -1,\n argsLength = args.length,\n holdersIndex = -1,\n holdersLength = holders.length,\n rightIndex = -1,\n rightLength = partials.length,\n rangeLength = nativeMax(argsLength - holdersLength, 0),\n result = Array(rangeLength + rightLength),\n isUncurried = !isCurried;\n\n while (++argsIndex < rangeLength) {\n result[argsIndex] = args[argsIndex];\n }\n var offset = argsIndex;\n while (++rightIndex < rightLength) {\n result[offset + rightIndex] = partials[rightIndex];\n }\n while (++holdersIndex < holdersLength) {\n if (isUncurried || argsIndex < argsLength) {\n result[offset + holders[holdersIndex]] = args[argsIndex++];\n }\n }\n return result;\n }\n\n /**\n * Copies the values of `source` to `array`.\n *\n * @private\n * @param {Array} source The array to copy values from.\n * @param {Array} [array=[]] The array to copy values to.\n * @returns {Array} Returns `array`.\n */\n function copyArray(source, array) {\n var index = -1,\n length = source.length;\n\n array || (array = Array(length));\n while (++index < length) {\n array[index] = source[index];\n }\n return array;\n }\n\n /**\n * Copies properties of `source` to `object`.\n *\n * @private\n * @param {Object} source The object to copy properties from.\n * @param {Array} props The property identifiers to copy.\n * @param {Object} [object={}] The object to copy properties to.\n * @param {Function} [customizer] The function to customize copied values.\n * @returns {Object} Returns `object`.\n */\n function copyObject(source, props, object, customizer) {\n var isNew = !object;\n object || (object = {});\n\n var index = -1,\n length = props.length;\n\n while (++index < length) {\n var key = props[index];\n\n var newValue = customizer\n ? customizer(object[key], source[key], key, object, source)\n : undefined;\n\n if (newValue === undefined) {\n newValue = source[key];\n }\n if (isNew) {\n baseAssignValue(object, key, newValue);\n } else {\n assignValue(object, key, newValue);\n }\n }\n return object;\n }\n\n /**\n * Copies own symbols of `source` to `object`.\n *\n * @private\n * @param {Object} source The object to copy symbols from.\n * @param {Object} [object={}] The object to copy symbols to.\n * @returns {Object} Returns `object`.\n */\n function copySymbols(source, object) {\n return copyObject(source, getSymbols(source), object);\n }\n\n /**\n * Copies own and inherited symbols of `source` to `object`.\n *\n * @private\n * @param {Object} source The object to copy symbols from.\n * @param {Object} [object={}] The object to copy symbols to.\n * @returns {Object} Returns `object`.\n */\n function copySymbolsIn(source, object) {\n return copyObject(source, getSymbolsIn(source), object);\n }\n\n /**\n * Creates a function like `_.groupBy`.\n *\n * @private\n * @param {Function} setter The function to set accumulator values.\n * @param {Function} [initializer] The accumulator object initializer.\n * @returns {Function} Returns the new aggregator function.\n */\n function createAggregator(setter, initializer) {\n return function(collection, iteratee) {\n var func = isArray(collection) ? arrayAggregator : baseAggregator,\n accumulator = initializer ? initializer() : {};\n\n return func(collection, setter, getIteratee(iteratee, 2), accumulator);\n };\n }\n\n /**\n * Creates a function like `_.assign`.\n *\n * @private\n * @param {Function} assigner The function to assign values.\n * @returns {Function} Returns the new assigner function.\n */\n function createAssigner(assigner) {\n return baseRest(function(object, sources) {\n var index = -1,\n length = sources.length,\n customizer = length > 1 ? sources[length - 1] : undefined,\n guard = length > 2 ? sources[2] : undefined;\n\n customizer = (assigner.length > 3 && typeof customizer == 'function')\n ? (length--, customizer)\n : undefined;\n\n if (guard && isIterateeCall(sources[0], sources[1], guard)) {\n customizer = length < 3 ? undefined : customizer;\n length = 1;\n }\n object = Object(object);\n while (++index < length) {\n var source = sources[index];\n if (source) {\n assigner(object, source, index, customizer);\n }\n }\n return object;\n });\n }\n\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 */\n function 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\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 */\n function 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\n /**\n * Creates a function that wraps `func` to invoke it with the optional `this`\n * binding of `thisArg`.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @param {*} [thisArg] The `this` binding of `func`.\n * @returns {Function} Returns the new wrapped function.\n */\n function createBind(func, bitmask, thisArg) {\n var isBind = bitmask & WRAP_BIND_FLAG,\n Ctor = createCtor(func);\n\n function wrapper() {\n var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;\n return fn.apply(isBind ? thisArg : this, arguments);\n }\n return wrapper;\n }\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 */\n function 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\n /**\n * Creates a function like `_.camelCase`.\n *\n * @private\n * @param {Function} callback The function to combine each word.\n * @returns {Function} Returns the new compounder function.\n */\n function createCompounder(callback) {\n return function(string) {\n return arrayReduce(words(deburr(string).replace(reApos, '')), callback, '');\n };\n }\n\n /**\n * Creates a function that produces an instance of `Ctor` regardless of\n * whether it was invoked as part of a `new` expression or by `call` or `apply`.\n *\n * @private\n * @param {Function} Ctor The constructor to wrap.\n * @returns {Function} Returns the new wrapped function.\n */\n function createCtor(Ctor) {\n return function() {\n // Use a `switch` statement to work with class constructors. See\n // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist\n // for more details.\n var args = arguments;\n switch (args.length) {\n case 0: return new Ctor;\n case 1: return new Ctor(args[0]);\n case 2: return new Ctor(args[0], args[1]);\n case 3: return new Ctor(args[0], args[1], args[2]);\n case 4: return new Ctor(args[0], args[1], args[2], args[3]);\n case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]);\n case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]);\n case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);\n }\n var thisBinding = baseCreate(Ctor.prototype),\n result = Ctor.apply(thisBinding, args);\n\n // Mimic the constructor's `return` behavior.\n // See https://es5.github.io/#x13.2.2 for more details.\n return isObject(result) ? result : thisBinding;\n };\n }\n\n /**\n * Creates a function that wraps `func` to enable currying.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @param {number} arity The arity of `func`.\n * @returns {Function} Returns the new wrapped function.\n */\n function createCurry(func, bitmask, arity) {\n var Ctor = createCtor(func);\n\n function wrapper() {\n var length = arguments.length,\n args = Array(length),\n index = length,\n placeholder = getHolder(wrapper);\n\n while (index--) {\n args[index] = arguments[index];\n }\n var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder)\n ? []\n : replaceHolders(args, placeholder);\n\n length -= holders.length;\n if (length < arity) {\n return createRecurry(\n func, bitmask, createHybrid, wrapper.placeholder, undefined,\n args, holders, undefined, undefined, arity - length);\n }\n var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;\n return apply(fn, this, args);\n }\n return wrapper;\n }\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 */\n function createFind(findIndexFunc) {\n return function(collection, predicate, fromIndex) {\n var iterable = Object(collection);\n if (!isArrayLike(collection)) {\n var iteratee = getIteratee(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\n /**\n * Creates a `_.flow` or `_.flowRight` function.\n *\n * @private\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new flow function.\n */\n function createFlow(fromRight) {\n return flatRest(function(funcs) {\n var length = funcs.length,\n index = length,\n prereq = LodashWrapper.prototype.thru;\n\n if (fromRight) {\n funcs.reverse();\n }\n while (index--) {\n var func = funcs[index];\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n if (prereq && !wrapper && getFuncName(func) == 'wrapper') {\n var wrapper = new LodashWrapper([], true);\n }\n }\n index = wrapper ? index : length;\n while (++index < length) {\n func = funcs[index];\n\n var funcName = getFuncName(func),\n data = funcName == 'wrapper' ? getData(func) : undefined;\n\n if (data && isLaziable(data[0]) &&\n data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) &&\n !data[4].length && data[9] == 1\n ) {\n wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]);\n } else {\n wrapper = (func.length == 1 && isLaziable(func))\n ? wrapper[funcName]()\n : wrapper.thru(func);\n }\n }\n return function() {\n var args = arguments,\n value = args[0];\n\n if (wrapper && args.length == 1 && isArray(value)) {\n return wrapper.plant(value).value();\n }\n var index = 0,\n result = length ? funcs[index].apply(this, args) : value;\n\n while (++index < length) {\n result = funcs[index].call(this, result);\n }\n return result;\n };\n });\n }\n\n /**\n * Creates a function that wraps `func` to invoke it with optional `this`\n * binding of `thisArg`, partial application, and currying.\n *\n * @private\n * @param {Function|string} func The function or method name to wrap.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @param {*} [thisArg] The `this` binding of `func`.\n * @param {Array} [partials] The arguments to prepend to those provided to\n * the new function.\n * @param {Array} [holders] The `partials` placeholder indexes.\n * @param {Array} [partialsRight] The arguments to append to those provided\n * to the new function.\n * @param {Array} [holdersRight] The `partialsRight` placeholder indexes.\n * @param {Array} [argPos] The argument positions of the new function.\n * @param {number} [ary] The arity cap of `func`.\n * @param {number} [arity] The arity of `func`.\n * @returns {Function} Returns the new wrapped function.\n */\n function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) {\n var isAry = bitmask & WRAP_ARY_FLAG,\n isBind = bitmask & WRAP_BIND_FLAG,\n isBindKey = bitmask & WRAP_BIND_KEY_FLAG,\n isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG),\n isFlip = bitmask & WRAP_FLIP_FLAG,\n Ctor = isBindKey ? undefined : createCtor(func);\n\n function wrapper() {\n var length = arguments.length,\n args = Array(length),\n index = length;\n\n while (index--) {\n args[index] = arguments[index];\n }\n if (isCurried) {\n var placeholder = getHolder(wrapper),\n holdersCount = countHolders(args, placeholder);\n }\n if (partials) {\n args = composeArgs(args, partials, holders, isCurried);\n }\n if (partialsRight) {\n args = composeArgsRight(args, partialsRight, holdersRight, isCurried);\n }\n length -= holdersCount;\n if (isCurried && length < arity) {\n var newHolders = replaceHolders(args, placeholder);\n return createRecurry(\n func, bitmask, createHybrid, wrapper.placeholder, thisArg,\n args, newHolders, argPos, ary, arity - length\n );\n }\n var thisBinding = isBind ? thisArg : this,\n fn = isBindKey ? thisBinding[func] : func;\n\n length = args.length;\n if (argPos) {\n args = reorder(args, argPos);\n } else if (isFlip && length > 1) {\n args.reverse();\n }\n if (isAry && ary < length) {\n args.length = ary;\n }\n if (this && this !== root && this instanceof wrapper) {\n fn = Ctor || createCtor(fn);\n }\n return fn.apply(thisBinding, args);\n }\n return wrapper;\n }\n\n /**\n * Creates a function like `_.invertBy`.\n *\n * @private\n * @param {Function} setter The function to set accumulator values.\n * @param {Function} toIteratee The function to resolve iteratees.\n * @returns {Function} Returns the new inverter function.\n */\n function createInverter(setter, toIteratee) {\n return function(object, iteratee) {\n return baseInverter(object, setter, toIteratee(iteratee), {});\n };\n }\n\n /**\n * Creates a function that performs a mathematical operation on two values.\n *\n * @private\n * @param {Function} operator The function to perform the operation.\n * @param {number} [defaultValue] The value used for `undefined` arguments.\n * @returns {Function} Returns the new mathematical operation function.\n */\n function createMathOperation(operator, defaultValue) {\n return function(value, other) {\n var result;\n if (value === undefined && other === undefined) {\n return defaultValue;\n }\n if (value !== undefined) {\n result = value;\n }\n if (other !== undefined) {\n if (result === undefined) {\n return other;\n }\n if (typeof value == 'string' || typeof other == 'string') {\n value = baseToString(value);\n other = baseToString(other);\n } else {\n value = baseToNumber(value);\n other = baseToNumber(other);\n }\n result = operator(value, other);\n }\n return result;\n };\n }\n\n /**\n * Creates a function like `_.over`.\n *\n * @private\n * @param {Function} arrayFunc The function to iterate over iteratees.\n * @returns {Function} Returns the new over function.\n */\n function createOver(arrayFunc) {\n return flatRest(function(iteratees) {\n iteratees = arrayMap(iteratees, baseUnary(getIteratee()));\n return baseRest(function(args) {\n var thisArg = this;\n return arrayFunc(iteratees, function(iteratee) {\n return apply(iteratee, thisArg, args);\n });\n });\n });\n }\n\n /**\n * Creates the padding for `string` based on `length`. The `chars` string\n * is truncated if the number of characters exceeds `length`.\n *\n * @private\n * @param {number} length The padding length.\n * @param {string} [chars=' '] The string used as padding.\n * @returns {string} Returns the padding for `string`.\n */\n function createPadding(length, chars) {\n chars = chars === undefined ? ' ' : baseToString(chars);\n\n var charsLength = chars.length;\n if (charsLength < 2) {\n return charsLength ? baseRepeat(chars, length) : chars;\n }\n var result = baseRepeat(chars, nativeCeil(length / stringSize(chars)));\n return hasUnicode(chars)\n ? castSlice(stringToArray(result), 0, length).join('')\n : result.slice(0, length);\n }\n\n /**\n * Creates a function that wraps `func` to invoke it with the `this` binding\n * of `thisArg` and `partials` prepended to the arguments it receives.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @param {*} thisArg The `this` binding of `func`.\n * @param {Array} partials The arguments to prepend to those provided to\n * the new function.\n * @returns {Function} Returns the new wrapped function.\n */\n function createPartial(func, bitmask, thisArg, partials) {\n var isBind = bitmask & WRAP_BIND_FLAG,\n Ctor = createCtor(func);\n\n function wrapper() {\n var argsIndex = -1,\n argsLength = arguments.length,\n leftIndex = -1,\n leftLength = partials.length,\n args = Array(leftLength + argsLength),\n fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;\n\n while (++leftIndex < leftLength) {\n args[leftIndex] = partials[leftIndex];\n }\n while (argsLength--) {\n args[leftIndex++] = arguments[++argsIndex];\n }\n return apply(fn, isBind ? thisArg : this, args);\n }\n return wrapper;\n }\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 */\n function 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\n /**\n * Creates a function that performs a relational operation on two values.\n *\n * @private\n * @param {Function} operator The function to perform the operation.\n * @returns {Function} Returns the new relational operation function.\n */\n function createRelationalOperation(operator) {\n return function(value, other) {\n if (!(typeof value == 'string' && typeof other == 'string')) {\n value = toNumber(value);\n other = toNumber(other);\n }\n return operator(value, other);\n };\n }\n\n /**\n * Creates a function that wraps `func` to continue currying.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @param {Function} wrapFunc The function to create the `func` wrapper.\n * @param {*} placeholder The placeholder value.\n * @param {*} [thisArg] The `this` binding of `func`.\n * @param {Array} [partials] The arguments to prepend to those provided to\n * the new function.\n * @param {Array} [holders] The `partials` placeholder indexes.\n * @param {Array} [argPos] The argument positions of the new function.\n * @param {number} [ary] The arity cap of `func`.\n * @param {number} [arity] The arity of `func`.\n * @returns {Function} Returns the new wrapped function.\n */\n function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) {\n var isCurry = bitmask & WRAP_CURRY_FLAG,\n newHolders = isCurry ? holders : undefined,\n newHoldersRight = isCurry ? undefined : holders,\n newPartials = isCurry ? partials : undefined,\n newPartialsRight = isCurry ? undefined : partials;\n\n bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG);\n bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG);\n\n if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) {\n bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG);\n }\n var newData = [\n func, bitmask, thisArg, newPartials, newHolders, newPartialsRight,\n newHoldersRight, argPos, ary, arity\n ];\n\n var result = wrapFunc.apply(undefined, newData);\n if (isLaziable(func)) {\n setData(result, newData);\n }\n result.placeholder = placeholder;\n return setWrapToString(result, func, bitmask);\n }\n\n /**\n * Creates a function like `_.round`.\n *\n * @private\n * @param {string} methodName The name of the `Math` method to use when rounding.\n * @returns {Function} Returns the new round function.\n */\n function createRound(methodName) {\n var func = Math[methodName];\n return function(number, precision) {\n number = toNumber(number);\n precision = precision == null ? 0 : nativeMin(toInteger(precision), 292);\n if (precision && nativeIsFinite(number)) {\n // Shift with exponential notation to avoid floating-point issues.\n // See [MDN](https://mdn.io/round#Examples) for more details.\n var pair = (toString(number) + 'e').split('e'),\n value = func(pair[0] + 'e' + (+pair[1] + precision));\n\n pair = (toString(value) + 'e').split('e');\n return +(pair[0] + 'e' + (+pair[1] - precision));\n }\n return func(number);\n };\n }\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 */\n var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) {\n return new Set(values);\n };\n\n /**\n * Creates a `_.toPairs` or `_.toPairsIn` function.\n *\n * @private\n * @param {Function} keysFunc The function to get the keys of a given object.\n * @returns {Function} Returns the new pairs function.\n */\n function createToPairs(keysFunc) {\n return function(object) {\n var tag = getTag(object);\n if (tag == mapTag) {\n return mapToArray(object);\n }\n if (tag == setTag) {\n return setToPairs(object);\n }\n return baseToPairs(object, keysFunc(object));\n };\n }\n\n /**\n * Creates a function that either curries or invokes `func` with optional\n * `this` binding and partially applied arguments.\n *\n * @private\n * @param {Function|string} func The function or method name to wrap.\n * @param {number} bitmask The bitmask flags.\n * 1 - `_.bind`\n * 2 - `_.bindKey`\n * 4 - `_.curry` or `_.curryRight` of a bound function\n * 8 - `_.curry`\n * 16 - `_.curryRight`\n * 32 - `_.partial`\n * 64 - `_.partialRight`\n * 128 - `_.rearg`\n * 256 - `_.ary`\n * 512 - `_.flip`\n * @param {*} [thisArg] The `this` binding of `func`.\n * @param {Array} [partials] The arguments to be partially applied.\n * @param {Array} [holders] The `partials` placeholder indexes.\n * @param {Array} [argPos] The argument positions of the new function.\n * @param {number} [ary] The arity cap of `func`.\n * @param {number} [arity] The arity of `func`.\n * @returns {Function} Returns the new wrapped function.\n */\n function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) {\n var isBindKey = bitmask & WRAP_BIND_KEY_FLAG;\n if (!isBindKey && typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n var length = partials ? partials.length : 0;\n if (!length) {\n bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG);\n partials = holders = undefined;\n }\n ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0);\n arity = arity === undefined ? arity : toInteger(arity);\n length -= holders ? holders.length : 0;\n\n if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) {\n var partialsRight = partials,\n holdersRight = holders;\n\n partials = holders = undefined;\n }\n var data = isBindKey ? undefined : getData(func);\n\n var newData = [\n func, bitmask, thisArg, partials, holders, partialsRight, holdersRight,\n argPos, ary, arity\n ];\n\n if (data) {\n mergeData(newData, data);\n }\n func = newData[0];\n bitmask = newData[1];\n thisArg = newData[2];\n partials = newData[3];\n holders = newData[4];\n arity = newData[9] = newData[9] === undefined\n ? (isBindKey ? 0 : func.length)\n : nativeMax(newData[9] - length, 0);\n\n if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) {\n bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG);\n }\n if (!bitmask || bitmask == WRAP_BIND_FLAG) {\n var result = createBind(func, bitmask, thisArg);\n } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) {\n result = createCurry(func, bitmask, arity);\n } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) {\n result = createPartial(func, bitmask, thisArg, partials);\n } else {\n result = createHybrid.apply(undefined, newData);\n }\n var setter = data ? baseSetData : setData;\n return setWrapToString(setter(result, newData), func, bitmask);\n }\n\n /**\n * Used by `_.defaults` to customize its `_.assignIn` use to assign properties\n * of source objects to the destination object for all destination properties\n * that resolve to `undefined`.\n *\n * @private\n * @param {*} objValue The destination value.\n * @param {*} srcValue The source value.\n * @param {string} key The key of the property to assign.\n * @param {Object} object The parent object of `objValue`.\n * @returns {*} Returns the value to assign.\n */\n function customDefaultsAssignIn(objValue, srcValue, key, object) {\n if (objValue === undefined ||\n (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) {\n return srcValue;\n }\n return objValue;\n }\n\n /**\n * Used by `_.defaultsDeep` to customize its `_.merge` use to merge source\n * objects into destination objects that are passed thru.\n *\n * @private\n * @param {*} objValue The destination value.\n * @param {*} srcValue The source value.\n * @param {string} key The key of the property to merge.\n * @param {Object} object The parent object of `objValue`.\n * @param {Object} source The parent object of `srcValue`.\n * @param {Object} [stack] Tracks traversed source values and their merged\n * counterparts.\n * @returns {*} Returns the value to assign.\n */\n function customDefaultsMerge(objValue, srcValue, key, object, source, stack) {\n if (isObject(objValue) && isObject(srcValue)) {\n // Recursively merge objects and arrays (susceptible to call stack limits).\n stack.set(srcValue, objValue);\n baseMerge(objValue, srcValue, undefined, customDefaultsMerge, stack);\n stack['delete'](srcValue);\n }\n return objValue;\n }\n\n /**\n * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain\n * objects.\n *\n * @private\n * @param {*} value The value to inspect.\n * @param {string} key The key of the property to inspect.\n * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`.\n */\n function customOmitClone(value) {\n return isPlainObject(value) ? undefined : value;\n }\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 */\n function 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\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 */\n function 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\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 */\n function 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\n /**\n * A specialized version of `baseRest` which flattens the rest array.\n *\n * @private\n * @param {Function} func The function to apply a rest parameter to.\n * @returns {Function} Returns the new function.\n */\n function flatRest(func) {\n return setToString(overRest(func, undefined, flatten), func + '');\n }\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 */\n function getAllKeys(object) {\n return baseGetAllKeys(object, keys, getSymbols);\n }\n\n /**\n * Creates an array of own and inherited enumerable property names and\n * symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names and symbols.\n */\n function getAllKeysIn(object) {\n return baseGetAllKeys(object, keysIn, getSymbolsIn);\n }\n\n /**\n * Gets metadata for `func`.\n *\n * @private\n * @param {Function} func The function to query.\n * @returns {*} Returns the metadata for `func`.\n */\n var getData = !metaMap ? noop : function(func) {\n return metaMap.get(func);\n };\n\n /**\n * Gets the name of `func`.\n *\n * @private\n * @param {Function} func The function to query.\n * @returns {string} Returns the function name.\n */\n function getFuncName(func) {\n var result = (func.name + ''),\n array = realNames[result],\n length = hasOwnProperty.call(realNames, result) ? array.length : 0;\n\n while (length--) {\n var data = array[length],\n otherFunc = data.func;\n if (otherFunc == null || otherFunc == func) {\n return data.name;\n }\n }\n return result;\n }\n\n /**\n * Gets the argument placeholder value for `func`.\n *\n * @private\n * @param {Function} func The function to inspect.\n * @returns {*} Returns the placeholder value.\n */\n function getHolder(func) {\n var object = hasOwnProperty.call(lodash, 'placeholder') ? lodash : func;\n return object.placeholder;\n }\n\n /**\n * Gets the appropriate \"iteratee\" function. If `_.iteratee` is customized,\n * this function returns the custom method, otherwise it returns `baseIteratee`.\n * If arguments are provided, the chosen function is invoked with them and\n * its result is returned.\n *\n * @private\n * @param {*} [value] The value to convert to an iteratee.\n * @param {number} [arity] The arity of the created iteratee.\n * @returns {Function} Returns the chosen function or its result.\n */\n function getIteratee() {\n var result = lodash.iteratee || iteratee;\n result = result === iteratee ? baseIteratee : result;\n return arguments.length ? result(arguments[0], arguments[1]) : result;\n }\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 */\n function getMapData(map, key) {\n var data = map.__data__;\n return isKeyable(key)\n ? data[typeof key == 'string' ? 'string' : 'hash']\n : data.map;\n }\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 */\n function 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\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 */\n function getNative(object, key) {\n var value = getValue(object, key);\n return baseIsNative(value) ? value : undefined;\n }\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 */\n function 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\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 */\n var 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\n /**\n * Creates an array of the own and inherited enumerable symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of symbols.\n */\n var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) {\n var result = [];\n while (object) {\n arrayPush(result, getSymbols(object));\n object = getPrototype(object);\n }\n return result;\n };\n\n /**\n * Gets the `toStringTag` of `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\n var getTag = baseGetTag;\n\n // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.\n if ((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\n /**\n * Gets the view, applying any `transforms` to the `start` and `end` positions.\n *\n * @private\n * @param {number} start The start of the view.\n * @param {number} end The end of the view.\n * @param {Array} transforms The transformations to apply to the view.\n * @returns {Object} Returns an object containing the `start` and `end`\n * positions of the view.\n */\n function getView(start, end, transforms) {\n var index = -1,\n length = transforms.length;\n\n while (++index < length) {\n var data = transforms[index],\n size = data.size;\n\n switch (data.type) {\n case 'drop': start += size; break;\n case 'dropRight': end -= size; break;\n case 'take': end = nativeMin(end, start + size); break;\n case 'takeRight': start = nativeMax(start, end - size); break;\n }\n }\n return { 'start': start, 'end': end };\n }\n\n /**\n * Extracts wrapper details from the `source` body comment.\n *\n * @private\n * @param {string} source The source to inspect.\n * @returns {Array} Returns the wrapper details.\n */\n function getWrapDetails(source) {\n var match = source.match(reWrapDetails);\n return match ? match[1].split(reSplitDetails) : [];\n }\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 */\n function 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\n /**\n * Initializes an array clone.\n *\n * @private\n * @param {Array} array The array to clone.\n * @returns {Array} Returns the initialized clone.\n */\n function initCloneArray(array) {\n var length = array.length,\n result = new array.constructor(length);\n\n // Add properties assigned by `RegExp#exec`.\n if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {\n result.index = array.index;\n result.input = array.input;\n }\n return result;\n }\n\n /**\n * Initializes an object clone.\n *\n * @private\n * @param {Object} object The object to clone.\n * @returns {Object} Returns the initialized clone.\n */\n function initCloneObject(object) {\n return (typeof object.constructor == 'function' && !isPrototype(object))\n ? baseCreate(getPrototype(object))\n : {};\n }\n\n /**\n * Initializes an object clone based on its `toStringTag`.\n *\n * **Note:** This function only supports cloning values with tags of\n * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`.\n *\n * @private\n * @param {Object} object The object to clone.\n * @param {string} tag The `toStringTag` of the object to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the initialized clone.\n */\n function initCloneByTag(object, tag, isDeep) {\n var Ctor = object.constructor;\n switch (tag) {\n case arrayBufferTag:\n return cloneArrayBuffer(object);\n\n case boolTag:\n case dateTag:\n return new Ctor(+object);\n\n case dataViewTag:\n return cloneDataView(object, isDeep);\n\n case float32Tag: case float64Tag:\n case int8Tag: case int16Tag: case int32Tag:\n case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:\n return cloneTypedArray(object, isDeep);\n\n case mapTag:\n return new Ctor;\n\n case numberTag:\n case stringTag:\n return new Ctor(object);\n\n case regexpTag:\n return cloneRegExp(object);\n\n case setTag:\n return new Ctor;\n\n case symbolTag:\n return cloneSymbol(object);\n }\n }\n\n /**\n * Inserts wrapper `details` in a comment at the top of the `source` body.\n *\n * @private\n * @param {string} source The source to modify.\n * @returns {Array} details The details to insert.\n * @returns {string} Returns the modified source.\n */\n function insertWrapDetails(source, details) {\n var length = details.length;\n if (!length) {\n return source;\n }\n var lastIndex = length - 1;\n details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex];\n details = details.join(length > 2 ? ', ' : ' ');\n return source.replace(reWrapComment, '{\\n/* [wrapped with ' + details + '] */\\n');\n }\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 */\n function isFlattenable(value) {\n return isArray(value) || isArguments(value) ||\n !!(spreadableSymbol && value && value[spreadableSymbol]);\n }\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 */\n function 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\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 */\n function 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\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 */\n function 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\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 */\n function 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\n /**\n * Checks if `func` has a lazy counterpart.\n *\n * @private\n * @param {Function} func The function to check.\n * @returns {boolean} Returns `true` if `func` has a lazy counterpart,\n * else `false`.\n */\n function isLaziable(func) {\n var funcName = getFuncName(func),\n other = lodash[funcName];\n\n if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) {\n return false;\n }\n if (func === other) {\n return true;\n }\n var data = getData(other);\n return !!data && func === data[0];\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 */\n function isMasked(func) {\n return !!maskSrcKey && (maskSrcKey in func);\n }\n\n /**\n * Checks if `func` is capable of being masked.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `func` is maskable, else `false`.\n */\n var isMaskable = coreJsData ? isFunction : stubFalse;\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 */\n function isPrototype(value) {\n var Ctor = value && value.constructor,\n proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;\n\n return value === proto;\n }\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 */\n function isStrictComparable(value) {\n return value === value && !isObject(value);\n }\n\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 */\n function 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\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 */\n function 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\n /**\n * Merges the function metadata of `source` into `data`.\n *\n * Merging metadata reduces the number of wrappers used to invoke a function.\n * This is possible because methods like `_.bind`, `_.curry`, and `_.partial`\n * may be applied regardless of execution order. Methods like `_.ary` and\n * `_.rearg` modify function arguments, making the order in which they are\n * executed important, preventing the merging of metadata. However, we make\n * an exception for a safe combined case where curried functions have `_.ary`\n * and or `_.rearg` applied.\n *\n * @private\n * @param {Array} data The destination metadata.\n * @param {Array} source The source metadata.\n * @returns {Array} Returns `data`.\n */\n function mergeData(data, source) {\n var bitmask = data[1],\n srcBitmask = source[1],\n newBitmask = bitmask | srcBitmask,\n isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG);\n\n var isCombo =\n ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) ||\n ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) ||\n ((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG));\n\n // Exit early if metadata can't be merged.\n if (!(isCommon || isCombo)) {\n return data;\n }\n // Use source `thisArg` if available.\n if (srcBitmask & WRAP_BIND_FLAG) {\n data[2] = source[2];\n // Set when currying a bound function.\n newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG;\n }\n // Compose partial arguments.\n var value = source[3];\n if (value) {\n var partials = data[3];\n data[3] = partials ? composeArgs(partials, value, source[4]) : value;\n data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4];\n }\n // Compose partial right arguments.\n value = source[5];\n if (value) {\n partials = data[5];\n data[5] = partials ? composeArgsRight(partials, value, source[6]) : value;\n data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6];\n }\n // Use source `argPos` if available.\n value = source[7];\n if (value) {\n data[7] = value;\n }\n // Use source `ary` if it's smaller.\n if (srcBitmask & WRAP_ARY_FLAG) {\n data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]);\n }\n // Use source `arity` if one is not provided.\n if (data[9] == null) {\n data[9] = source[9];\n }\n // Use source `func` and merge bitmasks.\n data[0] = source[0];\n data[1] = newBitmask;\n\n return data;\n }\n\n /**\n * This function is like\n * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * except that it includes inherited enumerable properties.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\n function nativeKeysIn(object) {\n var result = [];\n if (object != null) {\n for (var key in Object(object)) {\n result.push(key);\n }\n }\n return result;\n }\n\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 */\n function objectToString(value) {\n return nativeObjectToString.call(value);\n }\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 */\n function 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\n /**\n * Gets the parent value at `path` of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array} path The path to get the parent value of.\n * @returns {*} Returns the parent value.\n */\n function parent(object, path) {\n return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1));\n }\n\n /**\n * Reorder `array` according to the specified indexes where the element at\n * the first index is assigned as the first element, the element at\n * the second index is assigned as the second element, and so on.\n *\n * @private\n * @param {Array} array The array to reorder.\n * @param {Array} indexes The arranged array indexes.\n * @returns {Array} Returns `array`.\n */\n function reorder(array, indexes) {\n var arrLength = array.length,\n length = nativeMin(indexes.length, arrLength),\n oldArray = copyArray(array);\n\n while (length--) {\n var index = indexes[length];\n array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined;\n }\n return array;\n }\n\n /**\n * Gets the value at `key`, unless `key` is \"__proto__\" or \"constructor\".\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\n function safeGet(object, key) {\n if (key === 'constructor' && typeof object[key] === 'function') {\n return;\n }\n\n if (key == '__proto__') {\n return;\n }\n\n return object[key];\n }\n\n /**\n * Sets metadata for `func`.\n *\n * **Note:** If this function becomes hot, i.e. is invoked a lot in a short\n * period of time, it will trip its breaker and transition to an identity\n * function to avoid garbage collection pauses in V8. See\n * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070)\n * for more details.\n *\n * @private\n * @param {Function} func The function to associate metadata with.\n * @param {*} data The metadata.\n * @returns {Function} Returns `func`.\n */\n var setData = shortOut(baseSetData);\n\n /**\n * A simple wrapper around the global [`setTimeout`](https://mdn.io/setTimeout).\n *\n * @private\n * @param {Function} func The function to delay.\n * @param {number} wait The number of milliseconds to delay invocation.\n * @returns {number|Object} Returns the timer id or timeout object.\n */\n var setTimeout = ctxSetTimeout || function(func, wait) {\n return root.setTimeout(func, wait);\n };\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 */\n var setToString = shortOut(baseSetToString);\n\n /**\n * Sets the `toString` method of `wrapper` to mimic the source of `reference`\n * with wrapper details in a comment at the top of the source body.\n *\n * @private\n * @param {Function} wrapper The function to modify.\n * @param {Function} reference The reference function.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @returns {Function} Returns `wrapper`.\n */\n function setWrapToString(wrapper, reference, bitmask) {\n var source = (reference + '');\n return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask)));\n }\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 */\n function 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\n /**\n * A specialized version of `_.shuffle` which mutates and sets the size of `array`.\n *\n * @private\n * @param {Array} array The array to shuffle.\n * @param {number} [size=array.length] The size of `array`.\n * @returns {Array} Returns `array`.\n */\n function shuffleSelf(array, size) {\n var index = -1,\n length = array.length,\n lastIndex = length - 1;\n\n size = size === undefined ? length : size;\n while (++index < size) {\n var rand = baseRandom(index, lastIndex),\n value = array[rand];\n\n array[rand] = array[index];\n array[index] = value;\n }\n array.length = size;\n return array;\n }\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 */\n var 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\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 */\n function 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\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 */\n function 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\n /**\n * Updates wrapper `details` based on `bitmask` flags.\n *\n * @private\n * @returns {Array} details The details to modify.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @returns {Array} Returns `details`.\n */\n function updateWrapDetails(details, bitmask) {\n arrayEach(wrapFlags, function(pair) {\n var value = '_.' + pair[0];\n if ((bitmask & pair[1]) && !arrayIncludes(details, value)) {\n details.push(value);\n }\n });\n return details.sort();\n }\n\n /**\n * Creates a clone of `wrapper`.\n *\n * @private\n * @param {Object} wrapper The wrapper to clone.\n * @returns {Object} Returns the cloned wrapper.\n */\n function wrapperClone(wrapper) {\n if (wrapper instanceof LazyWrapper) {\n return wrapper.clone();\n }\n var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__);\n result.__actions__ = copyArray(wrapper.__actions__);\n result.__index__ = wrapper.__index__;\n result.__values__ = wrapper.__values__;\n return result;\n }\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates an array of elements split into groups the length of `size`.\n * If `array` can't be split evenly, the final chunk will be the remaining\n * elements.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to process.\n * @param {number} [size=1] The length of each chunk\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Array} Returns the new array of chunks.\n * @example\n *\n * _.chunk(['a', 'b', 'c', 'd'], 2);\n * // => [['a', 'b'], ['c', 'd']]\n *\n * _.chunk(['a', 'b', 'c', 'd'], 3);\n * // => [['a', 'b', 'c'], ['d']]\n */\n function chunk(array, size, guard) {\n if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) {\n size = 1;\n } else {\n size = nativeMax(toInteger(size), 0);\n }\n var length = array == null ? 0 : array.length;\n if (!length || size < 1) {\n return [];\n }\n var index = 0,\n resIndex = 0,\n result = Array(nativeCeil(length / size));\n\n while (index < length) {\n result[resIndex++] = baseSlice(array, index, (index += size));\n }\n return result;\n }\n\n /**\n * Creates an array with all falsey values removed. The values `false`, `null`,\n * `0`, `\"\"`, `undefined`, and `NaN` are falsey.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to compact.\n * @returns {Array} Returns the new array of filtered values.\n * @example\n *\n * _.compact([0, 1, false, 2, '', 3]);\n * // => [1, 2, 3]\n */\n function compact(array) {\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 (value) {\n result[resIndex++] = value;\n }\n }\n return result;\n }\n\n /**\n * Creates a new array concatenating `array` with any additional arrays\n * and/or values.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to concatenate.\n * @param {...*} [values] The values to concatenate.\n * @returns {Array} Returns the new concatenated array.\n * @example\n *\n * var array = [1];\n * var other = _.concat(array, 2, [3], [[4]]);\n *\n * console.log(other);\n * // => [1, 2, 3, [4]]\n *\n * console.log(array);\n * // => [1]\n */\n function concat() {\n var length = arguments.length;\n if (!length) {\n return [];\n }\n var args = Array(length - 1),\n array = arguments[0],\n index = length;\n\n while (index--) {\n args[index - 1] = arguments[index];\n }\n return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1));\n }\n\n /**\n * Creates an array of `array` values not included in the other given arrays\n * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons. The order and references of result values are\n * determined by the first array.\n *\n * **Note:** Unlike `_.pullAll`, this method returns a new array.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {...Array} [values] The values to exclude.\n * @returns {Array} Returns the new array of filtered values.\n * @see _.without, _.xor\n * @example\n *\n * _.difference([2, 1], [2, 3]);\n * // => [1]\n */\n var difference = baseRest(function(array, values) {\n return isArrayLikeObject(array)\n ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true))\n : [];\n });\n\n /**\n * This method is like `_.difference` except that it accepts `iteratee` which\n * is invoked for each element of `array` and `values` to generate the criterion\n * by which they're compared. The order and references of result values are\n * determined by the first array. The iteratee is invoked with one argument:\n * (value).\n *\n * **Note:** Unlike `_.pullAllBy`, this method returns a new array.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {...Array} [values] The values to exclude.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {Array} Returns the new array of filtered values.\n * @example\n *\n * _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor);\n * // => [1.2]\n *\n * // The `_.property` iteratee shorthand.\n * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x');\n * // => [{ 'x': 2 }]\n */\n var differenceBy = baseRest(function(array, values) {\n var iteratee = last(values);\n if (isArrayLikeObject(iteratee)) {\n iteratee = undefined;\n }\n return isArrayLikeObject(array)\n ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), getIteratee(iteratee, 2))\n : [];\n });\n\n /**\n * This method is like `_.difference` except that it accepts `comparator`\n * which is invoked to compare elements of `array` to `values`. The order and\n * references of result values are determined by the first array. The comparator\n * is invoked with two arguments: (arrVal, othVal).\n *\n * **Note:** Unlike `_.pullAllWith`, this method returns a new array.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {...Array} [values] The values to exclude.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new array of filtered values.\n * @example\n *\n * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];\n *\n * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual);\n * // => [{ 'x': 2, 'y': 1 }]\n */\n var differenceWith = baseRest(function(array, values) {\n var comparator = last(values);\n if (isArrayLikeObject(comparator)) {\n comparator = undefined;\n }\n return isArrayLikeObject(array)\n ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator)\n : [];\n });\n\n /**\n * Creates a slice of `array` with `n` elements dropped from the beginning.\n *\n * @static\n * @memberOf _\n * @since 0.5.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {number} [n=1] The number of elements to drop.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * _.drop([1, 2, 3]);\n * // => [2, 3]\n *\n * _.drop([1, 2, 3], 2);\n * // => [3]\n *\n * _.drop([1, 2, 3], 5);\n * // => []\n *\n * _.drop([1, 2, 3], 0);\n * // => [1, 2, 3]\n */\n function drop(array, n, guard) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return [];\n }\n n = (guard || n === undefined) ? 1 : toInteger(n);\n return baseSlice(array, n < 0 ? 0 : n, length);\n }\n\n /**\n * Creates a slice of `array` with `n` elements dropped from the end.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {number} [n=1] The number of elements to drop.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * _.dropRight([1, 2, 3]);\n * // => [1, 2]\n *\n * _.dropRight([1, 2, 3], 2);\n * // => [1]\n *\n * _.dropRight([1, 2, 3], 5);\n * // => []\n *\n * _.dropRight([1, 2, 3], 0);\n * // => [1, 2, 3]\n */\n function dropRight(array, n, guard) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return [];\n }\n n = (guard || n === undefined) ? 1 : toInteger(n);\n n = length - n;\n return baseSlice(array, 0, n < 0 ? 0 : n);\n }\n\n /**\n * Creates a slice of `array` excluding elements dropped from the end.\n * Elements are dropped until `predicate` returns falsey. The predicate is\n * invoked with three arguments: (value, index, array).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'active': true },\n * { 'user': 'fred', 'active': false },\n * { 'user': 'pebbles', 'active': false }\n * ];\n *\n * _.dropRightWhile(users, function(o) { return !o.active; });\n * // => objects for ['barney']\n *\n * // The `_.matches` iteratee shorthand.\n * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false });\n * // => objects for ['barney', 'fred']\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.dropRightWhile(users, ['active', false]);\n * // => objects for ['barney']\n *\n * // The `_.property` iteratee shorthand.\n * _.dropRightWhile(users, 'active');\n * // => objects for ['barney', 'fred', 'pebbles']\n */\n function dropRightWhile(array, predicate) {\n return (array && array.length)\n ? baseWhile(array, getIteratee(predicate, 3), true, true)\n : [];\n }\n\n /**\n * Creates a slice of `array` excluding elements dropped from the beginning.\n * Elements are dropped until `predicate` returns falsey. The predicate is\n * invoked with three arguments: (value, index, array).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'active': false },\n * { 'user': 'fred', 'active': false },\n * { 'user': 'pebbles', 'active': true }\n * ];\n *\n * _.dropWhile(users, function(o) { return !o.active; });\n * // => objects for ['pebbles']\n *\n * // The `_.matches` iteratee shorthand.\n * _.dropWhile(users, { 'user': 'barney', 'active': false });\n * // => objects for ['fred', 'pebbles']\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.dropWhile(users, ['active', false]);\n * // => objects for ['pebbles']\n *\n * // The `_.property` iteratee shorthand.\n * _.dropWhile(users, 'active');\n * // => objects for ['barney', 'fred', 'pebbles']\n */\n function dropWhile(array, predicate) {\n return (array && array.length)\n ? baseWhile(array, getIteratee(predicate, 3), true)\n : [];\n }\n\n /**\n * Fills elements of `array` with `value` from `start` up to, but not\n * including, `end`.\n *\n * **Note:** This method mutates `array`.\n *\n * @static\n * @memberOf _\n * @since 3.2.0\n * @category Array\n * @param {Array} array The array to fill.\n * @param {*} value The value to fill `array` with.\n * @param {number} [start=0] The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns `array`.\n * @example\n *\n * var array = [1, 2, 3];\n *\n * _.fill(array, 'a');\n * console.log(array);\n * // => ['a', 'a', 'a']\n *\n * _.fill(Array(3), 2);\n * // => [2, 2, 2]\n *\n * _.fill([4, 6, 8, 10], '*', 1, 3);\n * // => [4, '*', '*', 10]\n */\n function fill(array, value, start, end) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return [];\n }\n if (start && typeof start != 'number' && isIterateeCall(array, value, start)) {\n start = 0;\n end = length;\n }\n return baseFill(array, value, start, end);\n }\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 */\n function 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, getIteratee(predicate, 3), index);\n }\n\n /**\n * This method is like `_.findIndex` except that it iterates over elements\n * of `collection` from right to left.\n *\n * @static\n * @memberOf _\n * @since 2.0.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=array.length-1] 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': true },\n * { 'user': 'fred', 'active': false },\n * { 'user': 'pebbles', 'active': false }\n * ];\n *\n * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; });\n * // => 2\n *\n * // The `_.matches` iteratee shorthand.\n * _.findLastIndex(users, { 'user': 'barney', 'active': true });\n * // => 0\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.findLastIndex(users, ['active', false]);\n * // => 2\n *\n * // The `_.property` iteratee shorthand.\n * _.findLastIndex(users, 'active');\n * // => 0\n */\n function findLastIndex(array, predicate, fromIndex) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return -1;\n }\n var index = length - 1;\n if (fromIndex !== undefined) {\n index = toInteger(fromIndex);\n index = fromIndex < 0\n ? nativeMax(length + index, 0)\n : nativeMin(index, length - 1);\n }\n return baseFindIndex(array, getIteratee(predicate, 3), index, true);\n }\n\n /**\n * Flattens `array` a single level deep.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to flatten.\n * @returns {Array} Returns the new flattened array.\n * @example\n *\n * _.flatten([1, [2, [3, [4]], 5]]);\n * // => [1, 2, [3, [4]], 5]\n */\n function flatten(array) {\n var length = array == null ? 0 : array.length;\n return length ? baseFlatten(array, 1) : [];\n }\n\n /**\n * Recursively flattens `array`.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to flatten.\n * @returns {Array} Returns the new flattened array.\n * @example\n *\n * _.flattenDeep([1, [2, [3, [4]], 5]]);\n * // => [1, 2, 3, 4, 5]\n */\n function flattenDeep(array) {\n var length = array == null ? 0 : array.length;\n return length ? baseFlatten(array, INFINITY) : [];\n }\n\n /**\n * Recursively flatten `array` up to `depth` times.\n *\n * @static\n * @memberOf _\n * @since 4.4.0\n * @category Array\n * @param {Array} array The array to flatten.\n * @param {number} [depth=1] The maximum recursion depth.\n * @returns {Array} Returns the new flattened array.\n * @example\n *\n * var array = [1, [2, [3, [4]], 5]];\n *\n * _.flattenDepth(array, 1);\n * // => [1, 2, [3, [4]], 5]\n *\n * _.flattenDepth(array, 2);\n * // => [1, 2, 3, [4], 5]\n */\n function flattenDepth(array, depth) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return [];\n }\n depth = depth === undefined ? 1 : toInteger(depth);\n return baseFlatten(array, depth);\n }\n\n /**\n * The inverse of `_.toPairs`; this method returns an object composed\n * from key-value `pairs`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} pairs The key-value pairs.\n * @returns {Object} Returns the new object.\n * @example\n *\n * _.fromPairs([['a', 1], ['b', 2]]);\n * // => { 'a': 1, 'b': 2 }\n */\n function fromPairs(pairs) {\n var index = -1,\n length = pairs == null ? 0 : pairs.length,\n result = {};\n\n while (++index < length) {\n var pair = pairs[index];\n result[pair[0]] = pair[1];\n }\n return result;\n }\n\n /**\n * Gets the first element of `array`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @alias first\n * @category Array\n * @param {Array} array The array to query.\n * @returns {*} Returns the first element of `array`.\n * @example\n *\n * _.head([1, 2, 3]);\n * // => 1\n *\n * _.head([]);\n * // => undefined\n */\n function head(array) {\n return (array && array.length) ? array[0] : undefined;\n }\n\n /**\n * Gets the index at which the first occurrence of `value` is found in `array`\n * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons. If `fromIndex` is negative, it's used as the\n * offset from the end of `array`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} [fromIndex=0] The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n * @example\n *\n * _.indexOf([1, 2, 1, 2], 2);\n * // => 1\n *\n * // Search from the `fromIndex`.\n * _.indexOf([1, 2, 1, 2], 2, 2);\n * // => 3\n */\n function indexOf(array, value, 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 baseIndexOf(array, value, index);\n }\n\n /**\n * Gets all but 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 {Array} Returns the slice of `array`.\n * @example\n *\n * _.initial([1, 2, 3]);\n * // => [1, 2]\n */\n function initial(array) {\n var length = array == null ? 0 : array.length;\n return length ? baseSlice(array, 0, -1) : [];\n }\n\n /**\n * Creates an array of unique values that are included in all given arrays\n * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons. The order and references of result values are\n * determined by the first array.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @returns {Array} Returns the new array of intersecting values.\n * @example\n *\n * _.intersection([2, 1], [2, 3]);\n * // => [2]\n */\n var intersection = baseRest(function(arrays) {\n var mapped = arrayMap(arrays, castArrayLikeObject);\n return (mapped.length && mapped[0] === arrays[0])\n ? baseIntersection(mapped)\n : [];\n });\n\n /**\n * This method is like `_.intersection` except that it accepts `iteratee`\n * which is invoked for each element of each `arrays` to generate the criterion\n * by which they're compared. The order and references of result values are\n * determined by the first 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} [arrays] The arrays to inspect.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {Array} Returns the new array of intersecting values.\n * @example\n *\n * _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor);\n * // => [2.1]\n *\n * // The `_.property` iteratee shorthand.\n * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');\n * // => [{ 'x': 1 }]\n */\n var intersectionBy = baseRest(function(arrays) {\n var iteratee = last(arrays),\n mapped = arrayMap(arrays, castArrayLikeObject);\n\n if (iteratee === last(mapped)) {\n iteratee = undefined;\n } else {\n mapped.pop();\n }\n return (mapped.length && mapped[0] === arrays[0])\n ? baseIntersection(mapped, getIteratee(iteratee, 2))\n : [];\n });\n\n /**\n * This method is like `_.intersection` except that it accepts `comparator`\n * which is invoked to compare elements of `arrays`. The order and references\n * of result values are determined by the first array. The comparator is\n * invoked with two arguments: (arrVal, othVal).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new array of intersecting values.\n * @example\n *\n * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];\n * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];\n *\n * _.intersectionWith(objects, others, _.isEqual);\n * // => [{ 'x': 1, 'y': 2 }]\n */\n var intersectionWith = baseRest(function(arrays) {\n var comparator = last(arrays),\n mapped = arrayMap(arrays, castArrayLikeObject);\n\n comparator = typeof comparator == 'function' ? comparator : undefined;\n if (comparator) {\n mapped.pop();\n }\n return (mapped.length && mapped[0] === arrays[0])\n ? baseIntersection(mapped, undefined, comparator)\n : [];\n });\n\n /**\n * Converts all elements in `array` into a string separated by `separator`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to convert.\n * @param {string} [separator=','] The element separator.\n * @returns {string} Returns the joined string.\n * @example\n *\n * _.join(['a', 'b', 'c'], '~');\n * // => 'a~b~c'\n */\n function join(array, separator) {\n return array == null ? '' : nativeJoin.call(array, separator);\n }\n\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 */\n function last(array) {\n var length = array == null ? 0 : array.length;\n return length ? array[length - 1] : undefined;\n }\n\n /**\n * This method is like `_.indexOf` except that it iterates over elements of\n * `array` from right to left.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} [fromIndex=array.length-1] The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n * @example\n *\n * _.lastIndexOf([1, 2, 1, 2], 2);\n * // => 3\n *\n * // Search from the `fromIndex`.\n * _.lastIndexOf([1, 2, 1, 2], 2, 2);\n * // => 1\n */\n function lastIndexOf(array, value, fromIndex) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return -1;\n }\n var index = length;\n if (fromIndex !== undefined) {\n index = toInteger(fromIndex);\n index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1);\n }\n return value === value\n ? strictLastIndexOf(array, value, index)\n : baseFindIndex(array, baseIsNaN, index, true);\n }\n\n /**\n * Gets the element at index `n` of `array`. If `n` is negative, the nth\n * element from the end is returned.\n *\n * @static\n * @memberOf _\n * @since 4.11.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {number} [n=0] The index of the element to return.\n * @returns {*} Returns the nth element of `array`.\n * @example\n *\n * var array = ['a', 'b', 'c', 'd'];\n *\n * _.nth(array, 1);\n * // => 'b'\n *\n * _.nth(array, -2);\n * // => 'c';\n */\n function nth(array, n) {\n return (array && array.length) ? baseNth(array, toInteger(n)) : undefined;\n }\n\n /**\n * Removes all given values from `array` using\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons.\n *\n * **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove`\n * to remove elements from an array by predicate.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @category Array\n * @param {Array} array The array to modify.\n * @param {...*} [values] The values to remove.\n * @returns {Array} Returns `array`.\n * @example\n *\n * var array = ['a', 'b', 'c', 'a', 'b', 'c'];\n *\n * _.pull(array, 'a', 'c');\n * console.log(array);\n * // => ['b', 'b']\n */\n var pull = baseRest(pullAll);\n\n /**\n * This method is like `_.pull` except that it accepts an array of values to remove.\n *\n * **Note:** Unlike `_.difference`, this method mutates `array`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to modify.\n * @param {Array} values The values to remove.\n * @returns {Array} Returns `array`.\n * @example\n *\n * var array = ['a', 'b', 'c', 'a', 'b', 'c'];\n *\n * _.pullAll(array, ['a', 'c']);\n * console.log(array);\n * // => ['b', 'b']\n */\n function pullAll(array, values) {\n return (array && array.length && values && values.length)\n ? basePullAll(array, values)\n : array;\n }\n\n /**\n * This method is like `_.pullAll` except that it accepts `iteratee` which is\n * invoked for each element of `array` and `values` to generate the criterion\n * by which they're compared. The iteratee is invoked with one argument: (value).\n *\n * **Note:** Unlike `_.differenceBy`, this method mutates `array`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to modify.\n * @param {Array} values The values to remove.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {Array} Returns `array`.\n * @example\n *\n * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }];\n *\n * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x');\n * console.log(array);\n * // => [{ 'x': 2 }]\n */\n function pullAllBy(array, values, iteratee) {\n return (array && array.length && values && values.length)\n ? basePullAll(array, values, getIteratee(iteratee, 2))\n : array;\n }\n\n /**\n * This method is like `_.pullAll` except that it accepts `comparator` which\n * is invoked to compare elements of `array` to `values`. The comparator is\n * invoked with two arguments: (arrVal, othVal).\n *\n * **Note:** Unlike `_.differenceWith`, this method mutates `array`.\n *\n * @static\n * @memberOf _\n * @since 4.6.0\n * @category Array\n * @param {Array} array The array to modify.\n * @param {Array} values The values to remove.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns `array`.\n * @example\n *\n * var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }];\n *\n * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual);\n * console.log(array);\n * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }]\n */\n function pullAllWith(array, values, comparator) {\n return (array && array.length && values && values.length)\n ? basePullAll(array, values, undefined, comparator)\n : array;\n }\n\n /**\n * Removes elements from `array` corresponding to `indexes` and returns an\n * array of removed elements.\n *\n * **Note:** Unlike `_.at`, this method mutates `array`.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to modify.\n * @param {...(number|number[])} [indexes] The indexes of elements to remove.\n * @returns {Array} Returns the new array of removed elements.\n * @example\n *\n * var array = ['a', 'b', 'c', 'd'];\n * var pulled = _.pullAt(array, [1, 3]);\n *\n * console.log(array);\n * // => ['a', 'c']\n *\n * console.log(pulled);\n * // => ['b', 'd']\n */\n var pullAt = flatRest(function(array, indexes) {\n var length = array == null ? 0 : array.length,\n result = baseAt(array, indexes);\n\n basePullAt(array, arrayMap(indexes, function(index) {\n return isIndex(index, length) ? +index : index;\n }).sort(compareAscending));\n\n return result;\n });\n\n /**\n * Removes all elements from `array` that `predicate` returns truthy for\n * and returns an array of the removed elements. The predicate is invoked\n * with three arguments: (value, index, array).\n *\n * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull`\n * to pull elements from an array by value.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @category Array\n * @param {Array} array The array to modify.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the new array of removed elements.\n * @example\n *\n * var array = [1, 2, 3, 4];\n * var evens = _.remove(array, function(n) {\n * return n % 2 == 0;\n * });\n *\n * console.log(array);\n * // => [1, 3]\n *\n * console.log(evens);\n * // => [2, 4]\n */\n function remove(array, predicate) {\n var result = [];\n if (!(array && array.length)) {\n return result;\n }\n var index = -1,\n indexes = [],\n length = array.length;\n\n predicate = getIteratee(predicate, 3);\n while (++index < length) {\n var value = array[index];\n if (predicate(value, index, array)) {\n result.push(value);\n indexes.push(index);\n }\n }\n basePullAt(array, indexes);\n return result;\n }\n\n /**\n * Reverses `array` so that the first element becomes the last, the second\n * element becomes the second to last, and so on.\n *\n * **Note:** This method mutates `array` and is based on\n * [`Array#reverse`](https://mdn.io/Array/reverse).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to modify.\n * @returns {Array} Returns `array`.\n * @example\n *\n * var array = [1, 2, 3];\n *\n * _.reverse(array);\n * // => [3, 2, 1]\n *\n * console.log(array);\n * // => [3, 2, 1]\n */\n function reverse(array) {\n return array == null ? array : nativeReverse.call(array);\n }\n\n /**\n * Creates a slice of `array` from `start` up to, but not including, `end`.\n *\n * **Note:** This method is used instead of\n * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are\n * returned.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\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 */\n function slice(array, start, end) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return [];\n }\n if (end && typeof end != 'number' && isIterateeCall(array, start, end)) {\n start = 0;\n end = length;\n }\n else {\n start = start == null ? 0 : toInteger(start);\n end = end === undefined ? length : toInteger(end);\n }\n return baseSlice(array, start, end);\n }\n\n /**\n * Uses a binary search to determine the lowest index at which `value`\n * should be inserted into `array` in order to maintain its sort order.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The sorted array to inspect.\n * @param {*} value The value to evaluate.\n * @returns {number} Returns the index at which `value` should be inserted\n * into `array`.\n * @example\n *\n * _.sortedIndex([30, 50], 40);\n * // => 1\n */\n function sortedIndex(array, value) {\n return baseSortedIndex(array, value);\n }\n\n /**\n * This method is like `_.sortedIndex` except that it accepts `iteratee`\n * which is invoked for `value` and each element of `array` to compute their\n * sort ranking. The iteratee is invoked with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The sorted array to inspect.\n * @param {*} value The value to evaluate.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {number} Returns the index at which `value` should be inserted\n * into `array`.\n * @example\n *\n * var objects = [{ 'x': 4 }, { 'x': 5 }];\n *\n * _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; });\n * // => 0\n *\n * // The `_.property` iteratee shorthand.\n * _.sortedIndexBy(objects, { 'x': 4 }, 'x');\n * // => 0\n */\n function sortedIndexBy(array, value, iteratee) {\n return baseSortedIndexBy(array, value, getIteratee(iteratee, 2));\n }\n\n /**\n * This method is like `_.indexOf` except that it performs a binary\n * search on a sorted `array`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @returns {number} Returns the index of the matched value, else `-1`.\n * @example\n *\n * _.sortedIndexOf([4, 5, 5, 5, 6], 5);\n * // => 1\n */\n function sortedIndexOf(array, value) {\n var length = array == null ? 0 : array.length;\n if (length) {\n var index = baseSortedIndex(array, value);\n if (index < length && eq(array[index], value)) {\n return index;\n }\n }\n return -1;\n }\n\n /**\n * This method is like `_.sortedIndex` except that it returns the highest\n * index at which `value` should be inserted into `array` in order to\n * maintain its sort order.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The sorted array to inspect.\n * @param {*} value The value to evaluate.\n * @returns {number} Returns the index at which `value` should be inserted\n * into `array`.\n * @example\n *\n * _.sortedLastIndex([4, 5, 5, 5, 6], 5);\n * // => 4\n */\n function sortedLastIndex(array, value) {\n return baseSortedIndex(array, value, true);\n }\n\n /**\n * This method is like `_.sortedLastIndex` except that it accepts `iteratee`\n * which is invoked for `value` and each element of `array` to compute their\n * sort ranking. The iteratee is invoked with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The sorted array to inspect.\n * @param {*} value The value to evaluate.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {number} Returns the index at which `value` should be inserted\n * into `array`.\n * @example\n *\n * var objects = [{ 'x': 4 }, { 'x': 5 }];\n *\n * _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; });\n * // => 1\n *\n * // The `_.property` iteratee shorthand.\n * _.sortedLastIndexBy(objects, { 'x': 4 }, 'x');\n * // => 1\n */\n function sortedLastIndexBy(array, value, iteratee) {\n return baseSortedIndexBy(array, value, getIteratee(iteratee, 2), true);\n }\n\n /**\n * This method is like `_.lastIndexOf` except that it performs a binary\n * search on a sorted `array`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @returns {number} Returns the index of the matched value, else `-1`.\n * @example\n *\n * _.sortedLastIndexOf([4, 5, 5, 5, 6], 5);\n * // => 3\n */\n function sortedLastIndexOf(array, value) {\n var length = array == null ? 0 : array.length;\n if (length) {\n var index = baseSortedIndex(array, value, true) - 1;\n if (eq(array[index], value)) {\n return index;\n }\n }\n return -1;\n }\n\n /**\n * This method is like `_.uniq` except that it's designed and optimized\n * for sorted arrays.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @returns {Array} Returns the new duplicate free array.\n * @example\n *\n * _.sortedUniq([1, 1, 2]);\n * // => [1, 2]\n */\n function sortedUniq(array) {\n return (array && array.length)\n ? baseSortedUniq(array)\n : [];\n }\n\n /**\n * This method is like `_.uniqBy` except that it's designed and optimized\n * for sorted arrays.\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] The iteratee invoked per element.\n * @returns {Array} Returns the new duplicate free array.\n * @example\n *\n * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor);\n * // => [1.1, 2.3]\n */\n function sortedUniqBy(array, iteratee) {\n return (array && array.length)\n ? baseSortedUniq(array, getIteratee(iteratee, 2))\n : [];\n }\n\n /**\n * Gets all but the first element of `array`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to query.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * _.tail([1, 2, 3]);\n * // => [2, 3]\n */\n function tail(array) {\n var length = array == null ? 0 : array.length;\n return length ? baseSlice(array, 1, length) : [];\n }\n\n /**\n * Creates a slice of `array` with `n` elements taken from the beginning.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {number} [n=1] The number of elements to take.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * _.take([1, 2, 3]);\n * // => [1]\n *\n * _.take([1, 2, 3], 2);\n * // => [1, 2]\n *\n * _.take([1, 2, 3], 5);\n * // => [1, 2, 3]\n *\n * _.take([1, 2, 3], 0);\n * // => []\n */\n function take(array, n, guard) {\n if (!(array && array.length)) {\n return [];\n }\n n = (guard || n === undefined) ? 1 : toInteger(n);\n return baseSlice(array, 0, n < 0 ? 0 : n);\n }\n\n /**\n * Creates a slice of `array` with `n` elements taken from the end.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {number} [n=1] The number of elements to take.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * _.takeRight([1, 2, 3]);\n * // => [3]\n *\n * _.takeRight([1, 2, 3], 2);\n * // => [2, 3]\n *\n * _.takeRight([1, 2, 3], 5);\n * // => [1, 2, 3]\n *\n * _.takeRight([1, 2, 3], 0);\n * // => []\n */\n function takeRight(array, n, guard) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return [];\n }\n n = (guard || n === undefined) ? 1 : toInteger(n);\n n = length - n;\n return baseSlice(array, n < 0 ? 0 : n, length);\n }\n\n /**\n * Creates a slice of `array` with elements taken from the end. Elements are\n * taken until `predicate` returns falsey. The predicate is invoked with\n * three arguments: (value, index, array).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'active': true },\n * { 'user': 'fred', 'active': false },\n * { 'user': 'pebbles', 'active': false }\n * ];\n *\n * _.takeRightWhile(users, function(o) { return !o.active; });\n * // => objects for ['fred', 'pebbles']\n *\n * // The `_.matches` iteratee shorthand.\n * _.takeRightWhile(users, { 'user': 'pebbles', 'active': false });\n * // => objects for ['pebbles']\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.takeRightWhile(users, ['active', false]);\n * // => objects for ['fred', 'pebbles']\n *\n * // The `_.property` iteratee shorthand.\n * _.takeRightWhile(users, 'active');\n * // => []\n */\n function takeRightWhile(array, predicate) {\n return (array && array.length)\n ? baseWhile(array, getIteratee(predicate, 3), false, true)\n : [];\n }\n\n /**\n * Creates a slice of `array` with elements taken from the beginning. Elements\n * are taken until `predicate` returns falsey. The predicate is invoked with\n * three arguments: (value, index, array).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'active': false },\n * { 'user': 'fred', 'active': false },\n * { 'user': 'pebbles', 'active': true }\n * ];\n *\n * _.takeWhile(users, function(o) { return !o.active; });\n * // => objects for ['barney', 'fred']\n *\n * // The `_.matches` iteratee shorthand.\n * _.takeWhile(users, { 'user': 'barney', 'active': false });\n * // => objects for ['barney']\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.takeWhile(users, ['active', false]);\n * // => objects for ['barney', 'fred']\n *\n * // The `_.property` iteratee shorthand.\n * _.takeWhile(users, 'active');\n * // => []\n */\n function takeWhile(array, predicate) {\n return (array && array.length)\n ? baseWhile(array, getIteratee(predicate, 3))\n : [];\n }\n\n /**\n * Creates an array of unique values, in order, from all given arrays using\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @returns {Array} Returns the new array of combined values.\n * @example\n *\n * _.union([2], [1, 2]);\n * // => [2, 1]\n */\n var union = baseRest(function(arrays) {\n return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true));\n });\n\n /**\n * This method is like `_.union` except that it accepts `iteratee` which is\n * invoked for each element of each `arrays` to generate the criterion by\n * which uniqueness is computed. Result values are chosen from the first\n * array in which the value occurs. 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} [arrays] The arrays to inspect.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {Array} Returns the new array of combined values.\n * @example\n *\n * _.unionBy([2.1], [1.2, 2.3], Math.floor);\n * // => [2.1, 1.2]\n *\n * // The `_.property` iteratee shorthand.\n * _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');\n * // => [{ 'x': 1 }, { 'x': 2 }]\n */\n var unionBy = baseRest(function(arrays) {\n var iteratee = last(arrays);\n if (isArrayLikeObject(iteratee)) {\n iteratee = undefined;\n }\n return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee, 2));\n });\n\n /**\n * This method is like `_.union` except that it accepts `comparator` which\n * is invoked to compare elements of `arrays`. Result values are chosen from\n * the first array in which the value occurs. The comparator is invoked\n * with two arguments: (arrVal, othVal).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new array of combined values.\n * @example\n *\n * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];\n * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];\n *\n * _.unionWith(objects, others, _.isEqual);\n * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]\n */\n var unionWith = baseRest(function(arrays) {\n var comparator = last(arrays);\n comparator = typeof comparator == 'function' ? comparator : undefined;\n return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined, comparator);\n });\n\n /**\n * Creates a duplicate-free version of an array, using\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons, in which only the first occurrence of each element\n * is kept. The order of result values is determined by the order they occur\n * in the array.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @returns {Array} Returns the new duplicate free array.\n * @example\n *\n * _.uniq([2, 1, 2]);\n * // => [2, 1]\n */\n function uniq(array) {\n return (array && array.length) ? baseUniq(array) : [];\n }\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 */\n function uniqBy(array, iteratee) {\n return (array && array.length) ? baseUniq(array, getIteratee(iteratee, 2)) : [];\n }\n\n /**\n * This method is like `_.uniq` except that it accepts `comparator` which\n * is invoked to compare elements of `array`. The order of result values is\n * determined by the order they occur in the array.The comparator is invoked\n * with two arguments: (arrVal, othVal).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new duplicate free array.\n * @example\n *\n * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }];\n *\n * _.uniqWith(objects, _.isEqual);\n * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]\n */\n function uniqWith(array, comparator) {\n comparator = typeof comparator == 'function' ? comparator : undefined;\n return (array && array.length) ? baseUniq(array, undefined, comparator) : [];\n }\n\n /**\n * This method is like `_.zip` except that it accepts an array of grouped\n * elements and creates an array regrouping the elements to their pre-zip\n * configuration.\n *\n * @static\n * @memberOf _\n * @since 1.2.0\n * @category Array\n * @param {Array} array The array of grouped elements to process.\n * @returns {Array} Returns the new array of regrouped elements.\n * @example\n *\n * var zipped = _.zip(['a', 'b'], [1, 2], [true, false]);\n * // => [['a', 1, true], ['b', 2, false]]\n *\n * _.unzip(zipped);\n * // => [['a', 'b'], [1, 2], [true, false]]\n */\n function unzip(array) {\n if (!(array && array.length)) {\n return [];\n }\n var length = 0;\n array = arrayFilter(array, function(group) {\n if (isArrayLikeObject(group)) {\n length = nativeMax(group.length, length);\n return true;\n }\n });\n return baseTimes(length, function(index) {\n return arrayMap(array, baseProperty(index));\n });\n }\n\n /**\n * This method is like `_.unzip` except that it accepts `iteratee` to specify\n * how regrouped values should be combined. The iteratee is invoked with the\n * elements of each group: (...group).\n *\n * @static\n * @memberOf _\n * @since 3.8.0\n * @category Array\n * @param {Array} array The array of grouped elements to process.\n * @param {Function} [iteratee=_.identity] The function to combine\n * regrouped values.\n * @returns {Array} Returns the new array of regrouped elements.\n * @example\n *\n * var zipped = _.zip([1, 2], [10, 20], [100, 200]);\n * // => [[1, 10, 100], [2, 20, 200]]\n *\n * _.unzipWith(zipped, _.add);\n * // => [3, 30, 300]\n */\n function unzipWith(array, iteratee) {\n if (!(array && array.length)) {\n return [];\n }\n var result = unzip(array);\n if (iteratee == null) {\n return result;\n }\n return arrayMap(result, function(group) {\n return apply(iteratee, undefined, group);\n });\n }\n\n /**\n * Creates an array excluding all given values using\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons.\n *\n * **Note:** Unlike `_.pull`, this method returns a new array.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {...*} [values] The values to exclude.\n * @returns {Array} Returns the new array of filtered values.\n * @see _.difference, _.xor\n * @example\n *\n * _.without([2, 1, 2, 3], 1, 2);\n * // => [3]\n */\n var without = baseRest(function(array, values) {\n return isArrayLikeObject(array)\n ? baseDifference(array, values)\n : [];\n });\n\n /**\n * Creates an array of unique values that is the\n * [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference)\n * of the given arrays. The order of result values is determined by the order\n * they occur in the arrays.\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @returns {Array} Returns the new array of filtered values.\n * @see _.difference, _.without\n * @example\n *\n * _.xor([2, 1], [2, 3]);\n * // => [1, 3]\n */\n var xor = baseRest(function(arrays) {\n return baseXor(arrayFilter(arrays, isArrayLikeObject));\n });\n\n /**\n * This method is like `_.xor` except that it accepts `iteratee` which is\n * invoked for each element of each `arrays` to generate the criterion by\n * which by which they're compared. The order of result values is determined\n * by the order they occur in the arrays. The iteratee is invoked with one\n * argument: (value).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {Array} Returns the new array of filtered values.\n * @example\n *\n * _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor);\n * // => [1.2, 3.4]\n *\n * // The `_.property` iteratee shorthand.\n * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');\n * // => [{ 'x': 2 }]\n */\n var xorBy = baseRest(function(arrays) {\n var iteratee = last(arrays);\n if (isArrayLikeObject(iteratee)) {\n iteratee = undefined;\n }\n return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee, 2));\n });\n\n /**\n * This method is like `_.xor` except that it accepts `comparator` which is\n * invoked to compare elements of `arrays`. The order of result values is\n * determined by the order they occur in the arrays. The comparator is invoked\n * with two arguments: (arrVal, othVal).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new array of filtered values.\n * @example\n *\n * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];\n * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];\n *\n * _.xorWith(objects, others, _.isEqual);\n * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]\n */\n var xorWith = baseRest(function(arrays) {\n var comparator = last(arrays);\n comparator = typeof comparator == 'function' ? comparator : undefined;\n return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator);\n });\n\n /**\n * Creates an array of grouped elements, the first of which contains the\n * first elements of the given arrays, the second of which contains the\n * second elements of the given arrays, and so on.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {...Array} [arrays] The arrays to process.\n * @returns {Array} Returns the new array of grouped elements.\n * @example\n *\n * _.zip(['a', 'b'], [1, 2], [true, false]);\n * // => [['a', 1, true], ['b', 2, false]]\n */\n var zip = baseRest(unzip);\n\n /**\n * This method is like `_.fromPairs` except that it accepts two arrays,\n * one of property identifiers and one of corresponding values.\n *\n * @static\n * @memberOf _\n * @since 0.4.0\n * @category Array\n * @param {Array} [props=[]] The property identifiers.\n * @param {Array} [values=[]] The property values.\n * @returns {Object} Returns the new object.\n * @example\n *\n * _.zipObject(['a', 'b'], [1, 2]);\n * // => { 'a': 1, 'b': 2 }\n */\n function zipObject(props, values) {\n return baseZipObject(props || [], values || [], assignValue);\n }\n\n /**\n * This method is like `_.zipObject` except that it supports property paths.\n *\n * @static\n * @memberOf _\n * @since 4.1.0\n * @category Array\n * @param {Array} [props=[]] The property identifiers.\n * @param {Array} [values=[]] The property values.\n * @returns {Object} Returns the new object.\n * @example\n *\n * _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]);\n * // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } }\n */\n function zipObjectDeep(props, values) {\n return baseZipObject(props || [], values || [], baseSet);\n }\n\n /**\n * This method is like `_.zip` except that it accepts `iteratee` to specify\n * how grouped values should be combined. The iteratee is invoked with the\n * elements of each group: (...group).\n *\n * @static\n * @memberOf _\n * @since 3.8.0\n * @category Array\n * @param {...Array} [arrays] The arrays to process.\n * @param {Function} [iteratee=_.identity] The function to combine\n * grouped values.\n * @returns {Array} Returns the new array of grouped elements.\n * @example\n *\n * _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) {\n * return a + b + c;\n * });\n * // => [111, 222]\n */\n var zipWith = baseRest(function(arrays) {\n var length = arrays.length,\n iteratee = length > 1 ? arrays[length - 1] : undefined;\n\n iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined;\n return unzipWith(arrays, iteratee);\n });\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates a `lodash` wrapper instance that wraps `value` with explicit method\n * chain sequences enabled. The result of such sequences must be unwrapped\n * with `_#value`.\n *\n * @static\n * @memberOf _\n * @since 1.3.0\n * @category Seq\n * @param {*} value The value to wrap.\n * @returns {Object} Returns the new `lodash` wrapper instance.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'age': 36 },\n * { 'user': 'fred', 'age': 40 },\n * { 'user': 'pebbles', 'age': 1 }\n * ];\n *\n * var youngest = _\n * .chain(users)\n * .sortBy('age')\n * .map(function(o) {\n * return o.user + ' is ' + o.age;\n * })\n * .head()\n * .value();\n * // => 'pebbles is 1'\n */\n function chain(value) {\n var result = lodash(value);\n result.__chain__ = true;\n return result;\n }\n\n /**\n * This method invokes `interceptor` and returns `value`. The interceptor\n * is invoked with one argument; (value). The purpose of this method is to\n * \"tap into\" a method chain sequence in order to modify intermediate results.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Seq\n * @param {*} value The value to provide to `interceptor`.\n * @param {Function} interceptor The function to invoke.\n * @returns {*} Returns `value`.\n * @example\n *\n * _([1, 2, 3])\n * .tap(function(array) {\n * // Mutate input array.\n * array.pop();\n * })\n * .reverse()\n * .value();\n * // => [2, 1]\n */\n function tap(value, interceptor) {\n interceptor(value);\n return value;\n }\n\n /**\n * This method is like `_.tap` except that it returns the result of `interceptor`.\n * The purpose of this method is to \"pass thru\" values replacing intermediate\n * results in a method chain sequence.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Seq\n * @param {*} value The value to provide to `interceptor`.\n * @param {Function} interceptor The function to invoke.\n * @returns {*} Returns the result of `interceptor`.\n * @example\n *\n * _(' abc ')\n * .chain()\n * .trim()\n * .thru(function(value) {\n * return [value];\n * })\n * .value();\n * // => ['abc']\n */\n function thru(value, interceptor) {\n return interceptor(value);\n }\n\n /**\n * This method is the wrapper version of `_.at`.\n *\n * @name at\n * @memberOf _\n * @since 1.0.0\n * @category Seq\n * @param {...(string|string[])} [paths] The property paths to pick.\n * @returns {Object} Returns the new `lodash` wrapper instance.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };\n *\n * _(object).at(['a[0].b.c', 'a[1]']).value();\n * // => [3, 4]\n */\n var wrapperAt = flatRest(function(paths) {\n var length = paths.length,\n start = length ? paths[0] : 0,\n value = this.__wrapped__,\n interceptor = function(object) { return baseAt(object, paths); };\n\n if (length > 1 || this.__actions__.length ||\n !(value instanceof LazyWrapper) || !isIndex(start)) {\n return this.thru(interceptor);\n }\n value = value.slice(start, +start + (length ? 1 : 0));\n value.__actions__.push({\n 'func': thru,\n 'args': [interceptor],\n 'thisArg': undefined\n });\n return new LodashWrapper(value, this.__chain__).thru(function(array) {\n if (length && !array.length) {\n array.push(undefined);\n }\n return array;\n });\n });\n\n /**\n * Creates a `lodash` wrapper instance with explicit method chain sequences enabled.\n *\n * @name chain\n * @memberOf _\n * @since 0.1.0\n * @category Seq\n * @returns {Object} Returns the new `lodash` wrapper instance.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'age': 36 },\n * { 'user': 'fred', 'age': 40 }\n * ];\n *\n * // A sequence without explicit chaining.\n * _(users).head();\n * // => { 'user': 'barney', 'age': 36 }\n *\n * // A sequence with explicit chaining.\n * _(users)\n * .chain()\n * .head()\n * .pick('user')\n * .value();\n * // => { 'user': 'barney' }\n */\n function wrapperChain() {\n return chain(this);\n }\n\n /**\n * Executes the chain sequence and returns the wrapped result.\n *\n * @name commit\n * @memberOf _\n * @since 3.2.0\n * @category Seq\n * @returns {Object} Returns the new `lodash` wrapper instance.\n * @example\n *\n * var array = [1, 2];\n * var wrapped = _(array).push(3);\n *\n * console.log(array);\n * // => [1, 2]\n *\n * wrapped = wrapped.commit();\n * console.log(array);\n * // => [1, 2, 3]\n *\n * wrapped.last();\n * // => 3\n *\n * console.log(array);\n * // => [1, 2, 3]\n */\n function wrapperCommit() {\n return new LodashWrapper(this.value(), this.__chain__);\n }\n\n /**\n * Gets the next value on a wrapped object following the\n * [iterator protocol](https://mdn.io/iteration_protocols#iterator).\n *\n * @name next\n * @memberOf _\n * @since 4.0.0\n * @category Seq\n * @returns {Object} Returns the next iterator value.\n * @example\n *\n * var wrapped = _([1, 2]);\n *\n * wrapped.next();\n * // => { 'done': false, 'value': 1 }\n *\n * wrapped.next();\n * // => { 'done': false, 'value': 2 }\n *\n * wrapped.next();\n * // => { 'done': true, 'value': undefined }\n */\n function wrapperNext() {\n if (this.__values__ === undefined) {\n this.__values__ = toArray(this.value());\n }\n var done = this.__index__ >= this.__values__.length,\n value = done ? undefined : this.__values__[this.__index__++];\n\n return { 'done': done, 'value': value };\n }\n\n /**\n * Enables the wrapper to be iterable.\n *\n * @name Symbol.iterator\n * @memberOf _\n * @since 4.0.0\n * @category Seq\n * @returns {Object} Returns the wrapper object.\n * @example\n *\n * var wrapped = _([1, 2]);\n *\n * wrapped[Symbol.iterator]() === wrapped;\n * // => true\n *\n * Array.from(wrapped);\n * // => [1, 2]\n */\n function wrapperToIterator() {\n return this;\n }\n\n /**\n * Creates a clone of the chain sequence planting `value` as the wrapped value.\n *\n * @name plant\n * @memberOf _\n * @since 3.2.0\n * @category Seq\n * @param {*} value The value to plant.\n * @returns {Object} Returns the new `lodash` wrapper instance.\n * @example\n *\n * function square(n) {\n * return n * n;\n * }\n *\n * var wrapped = _([1, 2]).map(square);\n * var other = wrapped.plant([3, 4]);\n *\n * other.value();\n * // => [9, 16]\n *\n * wrapped.value();\n * // => [1, 4]\n */\n function wrapperPlant(value) {\n var result,\n parent = this;\n\n while (parent instanceof baseLodash) {\n var clone = wrapperClone(parent);\n clone.__index__ = 0;\n clone.__values__ = undefined;\n if (result) {\n previous.__wrapped__ = clone;\n } else {\n result = clone;\n }\n var previous = clone;\n parent = parent.__wrapped__;\n }\n previous.__wrapped__ = value;\n return result;\n }\n\n /**\n * This method is the wrapper version of `_.reverse`.\n *\n * **Note:** This method mutates the wrapped array.\n *\n * @name reverse\n * @memberOf _\n * @since 0.1.0\n * @category Seq\n * @returns {Object} Returns the new `lodash` wrapper instance.\n * @example\n *\n * var array = [1, 2, 3];\n *\n * _(array).reverse().value()\n * // => [3, 2, 1]\n *\n * console.log(array);\n * // => [3, 2, 1]\n */\n function wrapperReverse() {\n var value = this.__wrapped__;\n if (value instanceof LazyWrapper) {\n var wrapped = value;\n if (this.__actions__.length) {\n wrapped = new LazyWrapper(this);\n }\n wrapped = wrapped.reverse();\n wrapped.__actions__.push({\n 'func': thru,\n 'args': [reverse],\n 'thisArg': undefined\n });\n return new LodashWrapper(wrapped, this.__chain__);\n }\n return this.thru(reverse);\n }\n\n /**\n * Executes the chain sequence to resolve the unwrapped value.\n *\n * @name value\n * @memberOf _\n * @since 0.1.0\n * @alias toJSON, valueOf\n * @category Seq\n * @returns {*} Returns the resolved unwrapped value.\n * @example\n *\n * _([1, 2, 3]).value();\n * // => [1, 2, 3]\n */\n function wrapperValue() {\n return baseWrapperValue(this.__wrapped__, this.__actions__);\n }\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates an object composed of keys generated from the results of running\n * each element of `collection` thru `iteratee`. The corresponding value of\n * each key is the number of times the key was returned by `iteratee`. The\n * iteratee is invoked with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 0.5.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The iteratee to transform keys.\n * @returns {Object} Returns the composed aggregate object.\n * @example\n *\n * _.countBy([6.1, 4.2, 6.3], Math.floor);\n * // => { '4': 1, '6': 2 }\n *\n * // The `_.property` iteratee shorthand.\n * _.countBy(['one', 'two', 'three'], 'length');\n * // => { '3': 2, '5': 1 }\n */\n var countBy = createAggregator(function(result, value, key) {\n if (hasOwnProperty.call(result, key)) {\n ++result[key];\n } else {\n baseAssignValue(result, key, 1);\n }\n });\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 */\n function 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, getIteratee(predicate, 3));\n }\n\n /**\n * Iterates over elements of `collection`, returning an array of all elements\n * `predicate` returns truthy for. The predicate is invoked with three\n * arguments: (value, index|key, collection).\n *\n * **Note:** Unlike `_.remove`, this method returns a new array.\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 * @returns {Array} Returns the new filtered array.\n * @see _.reject\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'age': 36, 'active': true },\n * { 'user': 'fred', 'age': 40, 'active': false }\n * ];\n *\n * _.filter(users, function(o) { return !o.active; });\n * // => objects for ['fred']\n *\n * // The `_.matches` iteratee shorthand.\n * _.filter(users, { 'age': 36, 'active': true });\n * // => objects for ['barney']\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.filter(users, ['active', false]);\n * // => objects for ['fred']\n *\n * // The `_.property` iteratee shorthand.\n * _.filter(users, 'active');\n * // => objects for ['barney']\n *\n * // Combining several predicates using `_.overEvery` or `_.overSome`.\n * _.filter(users, _.overSome([{ 'age': 36 }, ['age', 40]]));\n * // => objects for ['fred', 'barney']\n */\n function filter(collection, predicate) {\n var func = isArray(collection) ? arrayFilter : baseFilter;\n return func(collection, getIteratee(predicate, 3));\n }\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 */\n var find = createFind(findIndex);\n\n /**\n * This method is like `_.find` except that it iterates over elements of\n * `collection` from right to left.\n *\n * @static\n * @memberOf _\n * @since 2.0.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=collection.length-1] The index to search from.\n * @returns {*} Returns the matched element, else `undefined`.\n * @example\n *\n * _.findLast([1, 2, 3, 4], function(n) {\n * return n % 2 == 1;\n * });\n * // => 3\n */\n var findLast = createFind(findLastIndex);\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 */\n function flatMap(collection, iteratee) {\n return baseFlatten(map(collection, iteratee), 1);\n }\n\n /**\n * This method is like `_.flatMap` except that it recursively flattens the\n * mapped results.\n *\n * @static\n * @memberOf _\n * @since 4.7.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 * _.flatMapDeep([1, 2], duplicate);\n * // => [1, 1, 2, 2]\n */\n function flatMapDeep(collection, iteratee) {\n return baseFlatten(map(collection, iteratee), INFINITY);\n }\n\n /**\n * This method is like `_.flatMap` except that it recursively flattens the\n * mapped results up to `depth` times.\n *\n * @static\n * @memberOf _\n * @since 4.7.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 * @param {number} [depth=1] The maximum recursion depth.\n * @returns {Array} Returns the new flattened array.\n * @example\n *\n * function duplicate(n) {\n * return [[[n, n]]];\n * }\n *\n * _.flatMapDepth([1, 2], duplicate, 2);\n * // => [[1, 1], [2, 2]]\n */\n function flatMapDepth(collection, iteratee, depth) {\n depth = depth === undefined ? 1 : toInteger(depth);\n return baseFlatten(map(collection, iteratee), depth);\n }\n\n /**\n * Iterates over elements of `collection` and invokes `iteratee` for each element.\n * The iteratee is invoked with three arguments: (value, index|key, collection).\n * Iteratee functions may exit iteration early by explicitly returning `false`.\n *\n * **Note:** As with other \"Collections\" methods, objects with a \"length\"\n * property are iterated like arrays. To avoid this behavior use `_.forIn`\n * or `_.forOwn` for object iteration.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @alias each\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|Object} Returns `collection`.\n * @see _.forEachRight\n * @example\n *\n * _.forEach([1, 2], function(value) {\n * console.log(value);\n * });\n * // => Logs `1` then `2`.\n *\n * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) {\n * console.log(key);\n * });\n * // => Logs 'a' then 'b' (iteration order is not guaranteed).\n */\n function forEach(collection, iteratee) {\n var func = isArray(collection) ? arrayEach : baseEach;\n return func(collection, getIteratee(iteratee, 3));\n }\n\n /**\n * This method is like `_.forEach` except that it iterates over elements of\n * `collection` from right to left.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @alias eachRight\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|Object} Returns `collection`.\n * @see _.forEach\n * @example\n *\n * _.forEachRight([1, 2], function(value) {\n * console.log(value);\n * });\n * // => Logs `2` then `1`.\n */\n function forEachRight(collection, iteratee) {\n var func = isArray(collection) ? arrayEachRight : baseEachRight;\n return func(collection, getIteratee(iteratee, 3));\n }\n\n /**\n * Creates an object composed of keys generated from the results of running\n * each element of `collection` thru `iteratee`. The order of grouped values\n * is determined by the order they occur in `collection`. The corresponding\n * value of each key is an array of elements responsible for generating the\n * key. The iteratee is 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} [iteratee=_.identity] The iteratee to transform keys.\n * @returns {Object} Returns the composed aggregate object.\n * @example\n *\n * _.groupBy([6.1, 4.2, 6.3], Math.floor);\n * // => { '4': [4.2], '6': [6.1, 6.3] }\n *\n * // The `_.property` iteratee shorthand.\n * _.groupBy(['one', 'two', 'three'], 'length');\n * // => { '3': ['one', 'two'], '5': ['three'] }\n */\n var groupBy = createAggregator(function(result, value, key) {\n if (hasOwnProperty.call(result, key)) {\n result[key].push(value);\n } else {\n baseAssignValue(result, key, [value]);\n }\n });\n\n /**\n * Checks if `value` is in `collection`. If `collection` is a string, it's\n * checked for a substring of `value`, otherwise\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * is used for equality comparisons. If `fromIndex` is negative, it's used as\n * the offset from the end of `collection`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object|string} collection The collection to inspect.\n * @param {*} value The value to search for.\n * @param {number} [fromIndex=0] The index to search from.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.\n * @returns {boolean} Returns `true` if `value` is found, else `false`.\n * @example\n *\n * _.includes([1, 2, 3], 1);\n * // => true\n *\n * _.includes([1, 2, 3], 1, 2);\n * // => false\n *\n * _.includes({ 'a': 1, 'b': 2 }, 1);\n * // => true\n *\n * _.includes('abcd', 'bc');\n * // => true\n */\n function includes(collection, value, fromIndex, guard) {\n collection = isArrayLike(collection) ? collection : values(collection);\n fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0;\n\n var length = collection.length;\n if (fromIndex < 0) {\n fromIndex = nativeMax(length + fromIndex, 0);\n }\n return isString(collection)\n ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1)\n : (!!length && baseIndexOf(collection, value, fromIndex) > -1);\n }\n\n /**\n * Invokes the method at `path` of each element in `collection`, returning\n * an array of the results of each invoked method. Any additional arguments\n * are provided to each invoked method. If `path` is a function, it's invoked\n * for, and `this` bound to, each element in `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 {Array|Function|string} path The path of the method to invoke or\n * the function invoked per iteration.\n * @param {...*} [args] The arguments to invoke each method with.\n * @returns {Array} Returns the array of results.\n * @example\n *\n * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort');\n * // => [[1, 5, 7], [1, 2, 3]]\n *\n * _.invokeMap([123, 456], String.prototype.split, '');\n * // => [['1', '2', '3'], ['4', '5', '6']]\n */\n var invokeMap = baseRest(function(collection, path, args) {\n var index = -1,\n isFunc = typeof path == 'function',\n result = isArrayLike(collection) ? Array(collection.length) : [];\n\n baseEach(collection, function(value) {\n result[++index] = isFunc ? apply(path, value, args) : baseInvoke(value, path, args);\n });\n return result;\n });\n\n /**\n * Creates an object composed of keys generated from the results of running\n * each element of `collection` thru `iteratee`. The corresponding value of\n * each key is the last element responsible for generating the key. The\n * iteratee is invoked with one argument: (value).\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 iteratee to transform keys.\n * @returns {Object} Returns the composed aggregate object.\n * @example\n *\n * var array = [\n * { 'dir': 'left', 'code': 97 },\n * { 'dir': 'right', 'code': 100 }\n * ];\n *\n * _.keyBy(array, function(o) {\n * return String.fromCharCode(o.code);\n * });\n * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }\n *\n * _.keyBy(array, 'dir');\n * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }\n */\n var keyBy = createAggregator(function(result, value, key) {\n baseAssignValue(result, key, value);\n });\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 */\n function map(collection, iteratee) {\n var func = isArray(collection) ? arrayMap : baseMap;\n return func(collection, getIteratee(iteratee, 3));\n }\n\n /**\n * This method is like `_.sortBy` except that it allows specifying the sort\n * orders of the iteratees to sort by. If `orders` is unspecified, all values\n * are sorted in ascending order. Otherwise, specify an order of \"desc\" for\n * descending or \"asc\" for ascending sort order of corresponding values.\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 {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]]\n * The iteratees to sort by.\n * @param {string[]} [orders] The sort orders of `iteratees`.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.\n * @returns {Array} Returns the new sorted array.\n * @example\n *\n * var users = [\n * { 'user': 'fred', 'age': 48 },\n * { 'user': 'barney', 'age': 34 },\n * { 'user': 'fred', 'age': 40 },\n * { 'user': 'barney', 'age': 36 }\n * ];\n *\n * // Sort by `user` in ascending order and by `age` in descending order.\n * _.orderBy(users, ['user', 'age'], ['asc', 'desc']);\n * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]\n */\n function orderBy(collection, iteratees, orders, guard) {\n if (collection == null) {\n return [];\n }\n if (!isArray(iteratees)) {\n iteratees = iteratees == null ? [] : [iteratees];\n }\n orders = guard ? undefined : orders;\n if (!isArray(orders)) {\n orders = orders == null ? [] : [orders];\n }\n return baseOrderBy(collection, iteratees, orders);\n }\n\n /**\n * Creates an array of elements split into two groups, the first of which\n * contains elements `predicate` returns truthy for, the second of which\n * contains elements `predicate` returns falsey for. The predicate is\n * invoked with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 3.0.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 * @returns {Array} Returns the array of grouped elements.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'age': 36, 'active': false },\n * { 'user': 'fred', 'age': 40, 'active': true },\n * { 'user': 'pebbles', 'age': 1, 'active': false }\n * ];\n *\n * _.partition(users, function(o) { return o.active; });\n * // => objects for [['fred'], ['barney', 'pebbles']]\n *\n * // The `_.matches` iteratee shorthand.\n * _.partition(users, { 'age': 1, 'active': false });\n * // => objects for [['pebbles'], ['barney', 'fred']]\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.partition(users, ['active', false]);\n * // => objects for [['barney', 'pebbles'], ['fred']]\n *\n * // The `_.property` iteratee shorthand.\n * _.partition(users, 'active');\n * // => objects for [['fred'], ['barney', 'pebbles']]\n */\n var partition = createAggregator(function(result, value, key) {\n result[key ? 0 : 1].push(value);\n }, function() { return [[], []]; });\n\n /**\n * Reduces `collection` to a value which is the accumulated result of running\n * each element in `collection` thru `iteratee`, where each successive\n * invocation is supplied the return value of the previous. If `accumulator`\n * is not given, the first element of `collection` is used as the initial\n * value. The iteratee is invoked with four arguments:\n * (accumulator, value, index|key, collection).\n *\n * Many lodash methods are guarded to work as iteratees for methods like\n * `_.reduce`, `_.reduceRight`, and `_.transform`.\n *\n * The guarded methods are:\n * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`,\n * and `sortBy`\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 * @param {*} [accumulator] The initial value.\n * @returns {*} Returns the accumulated value.\n * @see _.reduceRight\n * @example\n *\n * _.reduce([1, 2], function(sum, n) {\n * return sum + n;\n * }, 0);\n * // => 3\n *\n * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {\n * (result[value] || (result[value] = [])).push(key);\n * return result;\n * }, {});\n * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed)\n */\n function reduce(collection, iteratee, accumulator) {\n var func = isArray(collection) ? arrayReduce : baseReduce,\n initAccum = arguments.length < 3;\n\n return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach);\n }\n\n /**\n * This method is like `_.reduce` except that it iterates over elements of\n * `collection` from right to left.\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 * @param {*} [accumulator] The initial value.\n * @returns {*} Returns the accumulated value.\n * @see _.reduce\n * @example\n *\n * var array = [[0, 1], [2, 3], [4, 5]];\n *\n * _.reduceRight(array, function(flattened, other) {\n * return flattened.concat(other);\n * }, []);\n * // => [4, 5, 2, 3, 0, 1]\n */\n function reduceRight(collection, iteratee, accumulator) {\n var func = isArray(collection) ? arrayReduceRight : baseReduce,\n initAccum = arguments.length < 3;\n\n return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight);\n }\n\n /**\n * The opposite of `_.filter`; this method returns the elements of `collection`\n * that `predicate` does **not** return truthy for.\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 * @returns {Array} Returns the new filtered array.\n * @see _.filter\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'age': 36, 'active': false },\n * { 'user': 'fred', 'age': 40, 'active': true }\n * ];\n *\n * _.reject(users, function(o) { return !o.active; });\n * // => objects for ['fred']\n *\n * // The `_.matches` iteratee shorthand.\n * _.reject(users, { 'age': 40, 'active': true });\n * // => objects for ['barney']\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.reject(users, ['active', false]);\n * // => objects for ['fred']\n *\n * // The `_.property` iteratee shorthand.\n * _.reject(users, 'active');\n * // => objects for ['barney']\n */\n function reject(collection, predicate) {\n var func = isArray(collection) ? arrayFilter : baseFilter;\n return func(collection, negate(getIteratee(predicate, 3)));\n }\n\n /**\n * Gets a random element from `collection`.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @category Collection\n * @param {Array|Object} collection The collection to sample.\n * @returns {*} Returns the random element.\n * @example\n *\n * _.sample([1, 2, 3, 4]);\n * // => 2\n */\n function sample(collection) {\n var func = isArray(collection) ? arraySample : baseSample;\n return func(collection);\n }\n\n /**\n * Gets `n` random elements at unique keys from `collection` up to the\n * size of `collection`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Collection\n * @param {Array|Object} collection The collection to sample.\n * @param {number} [n=1] The number of elements to sample.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Array} Returns the random elements.\n * @example\n *\n * _.sampleSize([1, 2, 3], 2);\n * // => [3, 1]\n *\n * _.sampleSize([1, 2, 3], 4);\n * // => [2, 3, 1]\n */\n function sampleSize(collection, n, guard) {\n if ((guard ? isIterateeCall(collection, n, guard) : n === undefined)) {\n n = 1;\n } else {\n n = toInteger(n);\n }\n var func = isArray(collection) ? arraySampleSize : baseSampleSize;\n return func(collection, n);\n }\n\n /**\n * Creates an array of shuffled values, using a version of the\n * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle).\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to shuffle.\n * @returns {Array} Returns the new shuffled array.\n * @example\n *\n * _.shuffle([1, 2, 3, 4]);\n * // => [4, 1, 3, 2]\n */\n function shuffle(collection) {\n var func = isArray(collection) ? arrayShuffle : baseShuffle;\n return func(collection);\n }\n\n /**\n * Gets the size of `collection` by returning its length for array-like\n * values or the number of own enumerable string keyed properties for objects.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object|string} collection The collection to inspect.\n * @returns {number} Returns the collection size.\n * @example\n *\n * _.size([1, 2, 3]);\n * // => 3\n *\n * _.size({ 'a': 1, 'b': 2 });\n * // => 2\n *\n * _.size('pebbles');\n * // => 7\n */\n function size(collection) {\n if (collection == null) {\n return 0;\n }\n if (isArrayLike(collection)) {\n return isString(collection) ? stringSize(collection) : collection.length;\n }\n var tag = getTag(collection);\n if (tag == mapTag || tag == setTag) {\n return collection.size;\n }\n return baseKeys(collection).length;\n }\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 */\n function 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, getIteratee(predicate, 3));\n }\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 */\n var 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\n /*------------------------------------------------------------------------*/\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 */\n var now = ctxNow || function() {\n return root.Date.now();\n };\n\n /*------------------------------------------------------------------------*/\n\n /**\n * The opposite of `_.before`; this method creates a function that invokes\n * `func` once it's called `n` or more times.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {number} n The number of calls before `func` is invoked.\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new restricted function.\n * @example\n *\n * var saves = ['profile', 'settings'];\n *\n * var done = _.after(saves.length, function() {\n * console.log('done saving!');\n * });\n *\n * _.forEach(saves, function(type) {\n * asyncSave({ 'type': type, 'complete': done });\n * });\n * // => Logs 'done saving!' after the two async saves have completed.\n */\n function after(n, func) {\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n n = toInteger(n);\n return function() {\n if (--n < 1) {\n return func.apply(this, arguments);\n }\n };\n }\n\n /**\n * Creates a function that invokes `func`, with up to `n` arguments,\n * ignoring any additional arguments.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Function\n * @param {Function} func The function to cap arguments for.\n * @param {number} [n=func.length] The arity cap.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Function} Returns the new capped function.\n * @example\n *\n * _.map(['6', '8', '10'], _.ary(parseInt, 1));\n * // => [6, 8, 10]\n */\n function ary(func, n, guard) {\n n = guard ? undefined : n;\n n = (func && n == null) ? func.length : n;\n return createWrap(func, WRAP_ARY_FLAG, undefined, undefined, undefined, undefined, n);\n }\n\n /**\n * Creates a function that invokes `func`, with the `this` binding and arguments\n * of the created function, while it's called less than `n` times. Subsequent\n * calls to the created function return the result of the last `func` invocation.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Function\n * @param {number} n The number of calls at which `func` is no longer invoked.\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new restricted function.\n * @example\n *\n * jQuery(element).on('click', _.before(5, addContactToList));\n * // => Allows adding up to 4 contacts to the list.\n */\n function before(n, func) {\n var result;\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n n = toInteger(n);\n return function() {\n if (--n > 0) {\n result = func.apply(this, arguments);\n }\n if (n <= 1) {\n func = undefined;\n }\n return result;\n };\n }\n\n /**\n * Creates a function that invokes `func` with the `this` binding of `thisArg`\n * and `partials` prepended to the arguments it receives.\n *\n * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds,\n * may be used as a placeholder for partially applied arguments.\n *\n * **Note:** Unlike native `Function#bind`, this method doesn't set the \"length\"\n * property of bound functions.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to bind.\n * @param {*} thisArg The `this` binding of `func`.\n * @param {...*} [partials] The arguments to be partially applied.\n * @returns {Function} Returns the new bound function.\n * @example\n *\n * function greet(greeting, punctuation) {\n * return greeting + ' ' + this.user + punctuation;\n * }\n *\n * var object = { 'user': 'fred' };\n *\n * var bound = _.bind(greet, object, 'hi');\n * bound('!');\n * // => 'hi fred!'\n *\n * // Bound with placeholders.\n * var bound = _.bind(greet, object, _, '!');\n * bound('hi');\n * // => 'hi fred!'\n */\n var bind = baseRest(function(func, thisArg, partials) {\n var bitmask = WRAP_BIND_FLAG;\n if (partials.length) {\n var holders = replaceHolders(partials, getHolder(bind));\n bitmask |= WRAP_PARTIAL_FLAG;\n }\n return createWrap(func, bitmask, thisArg, partials, holders);\n });\n\n /**\n * Creates a function that invokes the method at `object[key]` with `partials`\n * prepended to the arguments it receives.\n *\n * This method differs from `_.bind` by allowing bound functions to reference\n * methods that may be redefined or don't yet exist. See\n * [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern)\n * for more details.\n *\n * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic\n * builds, may be used as a placeholder for partially applied arguments.\n *\n * @static\n * @memberOf _\n * @since 0.10.0\n * @category Function\n * @param {Object} object The object to invoke the method on.\n * @param {string} key The key of the method.\n * @param {...*} [partials] The arguments to be partially applied.\n * @returns {Function} Returns the new bound function.\n * @example\n *\n * var object = {\n * 'user': 'fred',\n * 'greet': function(greeting, punctuation) {\n * return greeting + ' ' + this.user + punctuation;\n * }\n * };\n *\n * var bound = _.bindKey(object, 'greet', 'hi');\n * bound('!');\n * // => 'hi fred!'\n *\n * object.greet = function(greeting, punctuation) {\n * return greeting + 'ya ' + this.user + punctuation;\n * };\n *\n * bound('!');\n * // => 'hiya fred!'\n *\n * // Bound with placeholders.\n * var bound = _.bindKey(object, 'greet', _, '!');\n * bound('hi');\n * // => 'hiya fred!'\n */\n var bindKey = baseRest(function(object, key, partials) {\n var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG;\n if (partials.length) {\n var holders = replaceHolders(partials, getHolder(bindKey));\n bitmask |= WRAP_PARTIAL_FLAG;\n }\n return createWrap(key, bitmask, object, partials, holders);\n });\n\n /**\n * Creates a function that accepts arguments of `func` and either invokes\n * `func` returning its result, if at least `arity` number of arguments have\n * been provided, or returns a function that accepts the remaining `func`\n * arguments, and so on. The arity of `func` may be specified if `func.length`\n * is not sufficient.\n *\n * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds,\n * may be used as a placeholder for provided arguments.\n *\n * **Note:** This method doesn't set the \"length\" property of curried functions.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @category Function\n * @param {Function} func The function to curry.\n * @param {number} [arity=func.length] The arity of `func`.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Function} Returns the new curried function.\n * @example\n *\n * var abc = function(a, b, c) {\n * return [a, b, c];\n * };\n *\n * var curried = _.curry(abc);\n *\n * curried(1)(2)(3);\n * // => [1, 2, 3]\n *\n * curried(1, 2)(3);\n * // => [1, 2, 3]\n *\n * curried(1, 2, 3);\n * // => [1, 2, 3]\n *\n * // Curried with placeholders.\n * curried(1)(_, 3)(2);\n * // => [1, 2, 3]\n */\n function curry(func, arity, guard) {\n arity = guard ? undefined : arity;\n var result = createWrap(func, WRAP_CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity);\n result.placeholder = curry.placeholder;\n return result;\n }\n\n /**\n * This method is like `_.curry` except that arguments are applied to `func`\n * in the manner of `_.partialRight` instead of `_.partial`.\n *\n * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic\n * builds, may be used as a placeholder for provided arguments.\n *\n * **Note:** This method doesn't set the \"length\" property of curried functions.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Function\n * @param {Function} func The function to curry.\n * @param {number} [arity=func.length] The arity of `func`.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Function} Returns the new curried function.\n * @example\n *\n * var abc = function(a, b, c) {\n * return [a, b, c];\n * };\n *\n * var curried = _.curryRight(abc);\n *\n * curried(3)(2)(1);\n * // => [1, 2, 3]\n *\n * curried(2, 3)(1);\n * // => [1, 2, 3]\n *\n * curried(1, 2, 3);\n * // => [1, 2, 3]\n *\n * // Curried with placeholders.\n * curried(3)(1, _)(2);\n * // => [1, 2, 3]\n */\n function curryRight(func, arity, guard) {\n arity = guard ? undefined : arity;\n var result = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity);\n result.placeholder = curryRight.placeholder;\n return result;\n }\n\n /**\n * Creates a debounced function that delays invoking `func` until after `wait`\n * milliseconds have elapsed since the last time the debounced function was\n * invoked. The debounced function comes with a `cancel` method to cancel\n * delayed `func` invocations and a `flush` method to immediately invoke them.\n * Provide `options` to indicate whether `func` should be invoked on the\n * leading and/or trailing edge of the `wait` timeout. The `func` is invoked\n * with the last arguments provided to the debounced function. Subsequent\n * calls to the debounced function return the result of the last `func`\n * invocation.\n *\n * **Note:** If `leading` and `trailing` options are `true`, `func` is\n * invoked on the trailing edge of the timeout only if the debounced function\n * is invoked more than once during the `wait` timeout.\n *\n * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred\n * until to the next tick, similar to `setTimeout` with a timeout of `0`.\n *\n * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)\n * for details over the differences between `_.debounce` and `_.throttle`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to debounce.\n * @param {number} [wait=0] The number of milliseconds to delay.\n * @param {Object} [options={}] The options object.\n * @param {boolean} [options.leading=false]\n * Specify invoking on the leading edge of the timeout.\n * @param {number} [options.maxWait]\n * The maximum time `func` is allowed to be delayed before it's invoked.\n * @param {boolean} [options.trailing=true]\n * Specify invoking on the trailing edge of the timeout.\n * @returns {Function} Returns the new debounced function.\n * @example\n *\n * // Avoid costly calculations while the window size is in flux.\n * jQuery(window).on('resize', _.debounce(calculateLayout, 150));\n *\n * // Invoke `sendMail` when clicked, debouncing subsequent calls.\n * jQuery(element).on('click', _.debounce(sendMail, 300, {\n * 'leading': true,\n * 'trailing': false\n * }));\n *\n * // Ensure `batchLog` is invoked once after 1 second of debounced calls.\n * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });\n * var source = new EventSource('/stream');\n * jQuery(source).on('message', debounced);\n *\n * // Cancel the trailing debounced invocation.\n * jQuery(window).on('popstate', debounced.cancel);\n */\n function 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\n /**\n * Defers invoking the `func` until the current call stack has cleared. Any\n * additional arguments are provided to `func` when it's invoked.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to defer.\n * @param {...*} [args] The arguments to invoke `func` with.\n * @returns {number} Returns the timer id.\n * @example\n *\n * _.defer(function(text) {\n * console.log(text);\n * }, 'deferred');\n * // => Logs 'deferred' after one millisecond.\n */\n var defer = baseRest(function(func, args) {\n return baseDelay(func, 1, args);\n });\n\n /**\n * Invokes `func` after `wait` milliseconds. Any additional arguments are\n * provided to `func` when it's invoked.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to delay.\n * @param {number} wait The number of milliseconds to delay invocation.\n * @param {...*} [args] The arguments to invoke `func` with.\n * @returns {number} Returns the timer id.\n * @example\n *\n * _.delay(function(text) {\n * console.log(text);\n * }, 1000, 'later');\n * // => Logs 'later' after one second.\n */\n var delay = baseRest(function(func, wait, args) {\n return baseDelay(func, toNumber(wait) || 0, args);\n });\n\n /**\n * Creates a function that invokes `func` with arguments reversed.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Function\n * @param {Function} func The function to flip arguments for.\n * @returns {Function} Returns the new flipped function.\n * @example\n *\n * var flipped = _.flip(function() {\n * return _.toArray(arguments);\n * });\n *\n * flipped('a', 'b', 'c', 'd');\n * // => ['d', 'c', 'b', 'a']\n */\n function flip(func) {\n return createWrap(func, WRAP_FLIP_FLAG);\n }\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 */\n function 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`.\n memoize.Cache = MapCache;\n\n /**\n * Creates a function that negates the result of the predicate `func`. The\n * `func` predicate is invoked with the `this` binding and arguments of the\n * created function.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Function\n * @param {Function} predicate The predicate to negate.\n * @returns {Function} Returns the new negated function.\n * @example\n *\n * function isEven(n) {\n * return n % 2 == 0;\n * }\n *\n * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));\n * // => [1, 3, 5]\n */\n function negate(predicate) {\n if (typeof predicate != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n return function() {\n var args = arguments;\n switch (args.length) {\n case 0: return !predicate.call(this);\n case 1: return !predicate.call(this, args[0]);\n case 2: return !predicate.call(this, args[0], args[1]);\n case 3: return !predicate.call(this, args[0], args[1], args[2]);\n }\n return !predicate.apply(this, args);\n };\n }\n\n /**\n * Creates a function that is restricted to invoking `func` once. Repeat calls\n * to the function return the value of the first invocation. The `func` is\n * invoked with the `this` binding and arguments of the created function.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new restricted function.\n * @example\n *\n * var initialize = _.once(createApplication);\n * initialize();\n * initialize();\n * // => `createApplication` is invoked once\n */\n function once(func) {\n return before(2, func);\n }\n\n /**\n * Creates a function that invokes `func` with its arguments transformed.\n *\n * @static\n * @since 4.0.0\n * @memberOf _\n * @category Function\n * @param {Function} func The function to wrap.\n * @param {...(Function|Function[])} [transforms=[_.identity]]\n * The argument transforms.\n * @returns {Function} Returns the new function.\n * @example\n *\n * function doubled(n) {\n * return n * 2;\n * }\n *\n * function square(n) {\n * return n * n;\n * }\n *\n * var func = _.overArgs(function(x, y) {\n * return [x, y];\n * }, [square, doubled]);\n *\n * func(9, 3);\n * // => [81, 6]\n *\n * func(10, 5);\n * // => [100, 10]\n */\n var overArgs = castRest(function(func, transforms) {\n transforms = (transforms.length == 1 && isArray(transforms[0]))\n ? arrayMap(transforms[0], baseUnary(getIteratee()))\n : arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee()));\n\n var funcsLength = transforms.length;\n return baseRest(function(args) {\n var index = -1,\n length = nativeMin(args.length, funcsLength);\n\n while (++index < length) {\n args[index] = transforms[index].call(this, args[index]);\n }\n return apply(func, this, args);\n });\n });\n\n /**\n * Creates a function that invokes `func` with `partials` prepended to the\n * arguments it receives. This method is like `_.bind` except it does **not**\n * alter the `this` binding.\n *\n * The `_.partial.placeholder` value, which defaults to `_` in monolithic\n * builds, may be used as a placeholder for partially applied arguments.\n *\n * **Note:** This method doesn't set the \"length\" property of partially\n * applied functions.\n *\n * @static\n * @memberOf _\n * @since 0.2.0\n * @category Function\n * @param {Function} func The function to partially apply arguments to.\n * @param {...*} [partials] The arguments to be partially applied.\n * @returns {Function} Returns the new partially applied function.\n * @example\n *\n * function greet(greeting, name) {\n * return greeting + ' ' + name;\n * }\n *\n * var sayHelloTo = _.partial(greet, 'hello');\n * sayHelloTo('fred');\n * // => 'hello fred'\n *\n * // Partially applied with placeholders.\n * var greetFred = _.partial(greet, _, 'fred');\n * greetFred('hi');\n * // => 'hi fred'\n */\n var partial = baseRest(function(func, partials) {\n var holders = replaceHolders(partials, getHolder(partial));\n return createWrap(func, WRAP_PARTIAL_FLAG, undefined, partials, holders);\n });\n\n /**\n * This method is like `_.partial` except that partially applied arguments\n * are appended to the arguments it receives.\n *\n * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic\n * builds, may be used as a placeholder for partially applied arguments.\n *\n * **Note:** This method doesn't set the \"length\" property of partially\n * applied functions.\n *\n * @static\n * @memberOf _\n * @since 1.0.0\n * @category Function\n * @param {Function} func The function to partially apply arguments to.\n * @param {...*} [partials] The arguments to be partially applied.\n * @returns {Function} Returns the new partially applied function.\n * @example\n *\n * function greet(greeting, name) {\n * return greeting + ' ' + name;\n * }\n *\n * var greetFred = _.partialRight(greet, 'fred');\n * greetFred('hi');\n * // => 'hi fred'\n *\n * // Partially applied with placeholders.\n * var sayHelloTo = _.partialRight(greet, 'hello', _);\n * sayHelloTo('fred');\n * // => 'hello fred'\n */\n var partialRight = baseRest(function(func, partials) {\n var holders = replaceHolders(partials, getHolder(partialRight));\n return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined, partials, holders);\n });\n\n /**\n * Creates a function that invokes `func` with arguments arranged according\n * to the specified `indexes` where the argument value at the first index is\n * provided as the first argument, the argument value at the second index is\n * provided as the second argument, and so on.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Function\n * @param {Function} func The function to rearrange arguments for.\n * @param {...(number|number[])} indexes The arranged argument indexes.\n * @returns {Function} Returns the new function.\n * @example\n *\n * var rearged = _.rearg(function(a, b, c) {\n * return [a, b, c];\n * }, [2, 0, 1]);\n *\n * rearged('b', 'c', 'a')\n * // => ['a', 'b', 'c']\n */\n var rearg = flatRest(function(func, indexes) {\n return createWrap(func, WRAP_REARG_FLAG, undefined, undefined, undefined, indexes);\n });\n\n /**\n * Creates a function that invokes `func` with the `this` binding of the\n * created function and arguments from `start` and beyond provided as\n * an array.\n *\n * **Note:** This method is based on the\n * [rest parameter](https://mdn.io/rest_parameters).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Function\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 * @example\n *\n * var say = _.rest(function(what, names) {\n * return what + ' ' + _.initial(names).join(', ') +\n * (_.size(names) > 1 ? ', & ' : '') + _.last(names);\n * });\n *\n * say('hello', 'fred', 'barney', 'pebbles');\n * // => 'hello fred, barney, & pebbles'\n */\n function rest(func, start) {\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n start = start === undefined ? start : toInteger(start);\n return baseRest(func, start);\n }\n\n /**\n * Creates a function that invokes `func` with the `this` binding of the\n * create function and an array of arguments much like\n * [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply).\n *\n * **Note:** This method is based on the\n * [spread operator](https://mdn.io/spread_operator).\n *\n * @static\n * @memberOf _\n * @since 3.2.0\n * @category Function\n * @param {Function} func The function to spread arguments over.\n * @param {number} [start=0] The start position of the spread.\n * @returns {Function} Returns the new function.\n * @example\n *\n * var say = _.spread(function(who, what) {\n * return who + ' says ' + what;\n * });\n *\n * say(['fred', 'hello']);\n * // => 'fred says hello'\n *\n * var numbers = Promise.all([\n * Promise.resolve(40),\n * Promise.resolve(36)\n * ]);\n *\n * numbers.then(_.spread(function(x, y) {\n * return x + y;\n * }));\n * // => a Promise of 76\n */\n function spread(func, start) {\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n start = start == null ? 0 : nativeMax(toInteger(start), 0);\n return baseRest(function(args) {\n var array = args[start],\n otherArgs = castSlice(args, 0, start);\n\n if (array) {\n arrayPush(otherArgs, array);\n }\n return apply(func, this, otherArgs);\n });\n }\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 */\n function 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\n /**\n * Creates a function that accepts up to one argument, ignoring any\n * additional arguments.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Function\n * @param {Function} func The function to cap arguments for.\n * @returns {Function} Returns the new capped function.\n * @example\n *\n * _.map(['6', '8', '10'], _.unary(parseInt));\n * // => [6, 8, 10]\n */\n function unary(func) {\n return ary(func, 1);\n }\n\n /**\n * Creates a function that provides `value` to `wrapper` as its first\n * argument. Any additional arguments provided to the function are appended\n * to those provided to the `wrapper`. The wrapper is invoked with the `this`\n * binding of the created function.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {*} value The value to wrap.\n * @param {Function} [wrapper=identity] The wrapper function.\n * @returns {Function} Returns the new function.\n * @example\n *\n * var p = _.wrap(_.escape, function(func, text) {\n * return '

    ' + func(text) + '

    ';\n * });\n *\n * p('fred, barney, & pebbles');\n * // => '

    fred, barney, & pebbles

    '\n */\n function wrap(value, wrapper) {\n return partial(castFunction(wrapper), value);\n }\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Casts `value` as an array if it's not one.\n *\n * @static\n * @memberOf _\n * @since 4.4.0\n * @category Lang\n * @param {*} value The value to inspect.\n * @returns {Array} Returns the cast array.\n * @example\n *\n * _.castArray(1);\n * // => [1]\n *\n * _.castArray({ 'a': 1 });\n * // => [{ 'a': 1 }]\n *\n * _.castArray('abc');\n * // => ['abc']\n *\n * _.castArray(null);\n * // => [null]\n *\n * _.castArray(undefined);\n * // => [undefined]\n *\n * _.castArray();\n * // => []\n *\n * var array = [1, 2, 3];\n * console.log(_.castArray(array) === array);\n * // => true\n */\n function castArray() {\n if (!arguments.length) {\n return [];\n }\n var value = arguments[0];\n return isArray(value) ? value : [value];\n }\n\n /**\n * Creates a shallow clone of `value`.\n *\n * **Note:** This method is loosely based on the\n * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm)\n * and supports cloning arrays, array buffers, booleans, date objects, maps,\n * numbers, `Object` objects, regexes, sets, strings, symbols, and typed\n * arrays. The own enumerable properties of `arguments` objects are cloned\n * as plain objects. An empty object is returned for uncloneable values such\n * as error objects, functions, DOM nodes, and WeakMaps.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to clone.\n * @returns {*} Returns the cloned value.\n * @see _.cloneDeep\n * @example\n *\n * var objects = [{ 'a': 1 }, { 'b': 2 }];\n *\n * var shallow = _.clone(objects);\n * console.log(shallow[0] === objects[0]);\n * // => true\n */\n function clone(value) {\n return baseClone(value, CLONE_SYMBOLS_FLAG);\n }\n\n /**\n * This method is like `_.clone` except that it accepts `customizer` which\n * is invoked to produce the cloned value. If `customizer` returns `undefined`,\n * cloning is handled by the method instead. The `customizer` is invoked with\n * up to four arguments; (value [, index|key, object, stack]).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to clone.\n * @param {Function} [customizer] The function to customize cloning.\n * @returns {*} Returns the cloned value.\n * @see _.cloneDeepWith\n * @example\n *\n * function customizer(value) {\n * if (_.isElement(value)) {\n * return value.cloneNode(false);\n * }\n * }\n *\n * var el = _.cloneWith(document.body, customizer);\n *\n * console.log(el === document.body);\n * // => false\n * console.log(el.nodeName);\n * // => 'BODY'\n * console.log(el.childNodes.length);\n * // => 0\n */\n function cloneWith(value, customizer) {\n customizer = typeof customizer == 'function' ? customizer : undefined;\n return baseClone(value, CLONE_SYMBOLS_FLAG, customizer);\n }\n\n /**\n * This method is like `_.clone` except that it recursively clones `value`.\n *\n * @static\n * @memberOf _\n * @since 1.0.0\n * @category Lang\n * @param {*} value The value to recursively clone.\n * @returns {*} Returns the deep cloned value.\n * @see _.clone\n * @example\n *\n * var objects = [{ 'a': 1 }, { 'b': 2 }];\n *\n * var deep = _.cloneDeep(objects);\n * console.log(deep[0] === objects[0]);\n * // => false\n */\n function cloneDeep(value) {\n return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG);\n }\n\n /**\n * This method is like `_.cloneWith` except that it recursively clones `value`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to recursively clone.\n * @param {Function} [customizer] The function to customize cloning.\n * @returns {*} Returns the deep cloned value.\n * @see _.cloneWith\n * @example\n *\n * function customizer(value) {\n * if (_.isElement(value)) {\n * return value.cloneNode(true);\n * }\n * }\n *\n * var el = _.cloneDeepWith(document.body, customizer);\n *\n * console.log(el === document.body);\n * // => false\n * console.log(el.nodeName);\n * // => 'BODY'\n * console.log(el.childNodes.length);\n * // => 20\n */\n function cloneDeepWith(value, customizer) {\n customizer = typeof customizer == 'function' ? customizer : undefined;\n return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer);\n }\n\n /**\n * Checks if `object` conforms to `source` by invoking the predicate\n * properties of `source` with the corresponding property values of `object`.\n *\n * **Note:** This method is equivalent to `_.conforms` when `source` is\n * partially applied.\n *\n * @static\n * @memberOf _\n * @since 4.14.0\n * @category Lang\n * @param {Object} object The object to inspect.\n * @param {Object} source The object of property predicates to conform to.\n * @returns {boolean} Returns `true` if `object` conforms, else `false`.\n * @example\n *\n * var object = { 'a': 1, 'b': 2 };\n *\n * _.conformsTo(object, { 'b': function(n) { return n > 1; } });\n * // => true\n *\n * _.conformsTo(object, { 'b': function(n) { return n > 2; } });\n * // => false\n */\n function conformsTo(object, source) {\n return source == null || baseConformsTo(object, source, keys(source));\n }\n\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 */\n function eq(value, other) {\n return value === other || (value !== value && other !== other);\n }\n\n /**\n * Checks if `value` is greater than `other`.\n *\n * @static\n * @memberOf _\n * @since 3.9.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 `value` is greater than `other`,\n * else `false`.\n * @see _.lt\n * @example\n *\n * _.gt(3, 1);\n * // => true\n *\n * _.gt(3, 3);\n * // => false\n *\n * _.gt(1, 3);\n * // => false\n */\n var gt = createRelationalOperation(baseGt);\n\n /**\n * Checks if `value` is greater than or equal to `other`.\n *\n * @static\n * @memberOf _\n * @since 3.9.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 `value` is greater than or equal to\n * `other`, else `false`.\n * @see _.lte\n * @example\n *\n * _.gte(3, 1);\n * // => true\n *\n * _.gte(3, 3);\n * // => true\n *\n * _.gte(1, 3);\n * // => false\n */\n var gte = createRelationalOperation(function(value, other) {\n return value >= other;\n });\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 */\n var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {\n return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&\n !propertyIsEnumerable.call(value, 'callee');\n };\n\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 */\n var isArray = Array.isArray;\n\n /**\n * Checks if `value` is classified as an `ArrayBuffer` object.\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 an array buffer, else `false`.\n * @example\n *\n * _.isArrayBuffer(new ArrayBuffer(2));\n * // => true\n *\n * _.isArrayBuffer(new Array(2));\n * // => false\n */\n var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer;\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 */\n function isArrayLike(value) {\n return value != null && isLength(value.length) && !isFunction(value);\n }\n\n /**\n * This method is like `_.isArrayLike` except that it also checks if `value`\n * is an object.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array-like object,\n * else `false`.\n * @example\n *\n * _.isArrayLikeObject([1, 2, 3]);\n * // => true\n *\n * _.isArrayLikeObject(document.body.children);\n * // => true\n *\n * _.isArrayLikeObject('abc');\n * // => false\n *\n * _.isArrayLikeObject(_.noop);\n * // => false\n */\n function isArrayLikeObject(value) {\n return isObjectLike(value) && isArrayLike(value);\n }\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 */\n function isBoolean(value) {\n return value === true || value === false ||\n (isObjectLike(value) && baseGetTag(value) == boolTag);\n }\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 */\n var isBuffer = nativeIsBuffer || stubFalse;\n\n /**\n * Checks if `value` is classified as a `Date` 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 date object, else `false`.\n * @example\n *\n * _.isDate(new Date);\n * // => true\n *\n * _.isDate('Mon April 23 2012');\n * // => false\n */\n var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate;\n\n /**\n * Checks if `value` is likely a DOM element.\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 DOM element, else `false`.\n * @example\n *\n * _.isElement(document.body);\n * // => true\n *\n * _.isElement('');\n * // => false\n */\n function isElement(value) {\n return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value);\n }\n\n /**\n * Checks if `value` is an empty object, collection, map, or set.\n *\n * Objects are considered empty if they have no own enumerable string keyed\n * properties.\n *\n * Array-like values such as `arguments` objects, arrays, buffers, strings, or\n * jQuery-like collections are considered empty if they have a `length` of `0`.\n * Similarly, maps and sets are considered empty if they have a `size` of `0`.\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 empty, else `false`.\n * @example\n *\n * _.isEmpty(null);\n * // => true\n *\n * _.isEmpty(true);\n * // => true\n *\n * _.isEmpty(1);\n * // => true\n *\n * _.isEmpty([1, 2, 3]);\n * // => false\n *\n * _.isEmpty({ 'a': 1 });\n * // => false\n */\n function isEmpty(value) {\n if (value == null) {\n return true;\n }\n if (isArrayLike(value) &&\n (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' ||\n isBuffer(value) || isTypedArray(value) || isArguments(value))) {\n return !value.length;\n }\n var tag = getTag(value);\n if (tag == mapTag || tag == setTag) {\n return !value.size;\n }\n if (isPrototype(value)) {\n return !baseKeys(value).length;\n }\n for (var key in value) {\n if (hasOwnProperty.call(value, key)) {\n return false;\n }\n }\n return true;\n }\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 */\n function isEqual(value, other) {\n return baseIsEqual(value, other);\n }\n\n /**\n * This method is like `_.isEqual` except that it accepts `customizer` which\n * is invoked to compare values. If `customizer` returns `undefined`, comparisons\n * are handled by the method instead. The `customizer` is invoked with up to\n * six arguments: (objValue, othValue [, index|key, object, other, stack]).\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 * @param {Function} [customizer] The function to customize comparisons.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * function isGreeting(value) {\n * return /^h(?:i|ello)$/.test(value);\n * }\n *\n * function customizer(objValue, othValue) {\n * if (isGreeting(objValue) && isGreeting(othValue)) {\n * return true;\n * }\n * }\n *\n * var array = ['hello', 'goodbye'];\n * var other = ['hi', 'goodbye'];\n *\n * _.isEqualWith(array, other, customizer);\n * // => true\n */\n function isEqualWith(value, other, customizer) {\n customizer = typeof customizer == 'function' ? customizer : undefined;\n var result = customizer ? customizer(value, other) : undefined;\n return result === undefined ? baseIsEqual(value, other, undefined, customizer) : !!result;\n }\n\n /**\n * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`,\n * `SyntaxError`, `TypeError`, or `URIError` object.\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 an error object, else `false`.\n * @example\n *\n * _.isError(new Error);\n * // => true\n *\n * _.isError(Error);\n * // => false\n */\n function isError(value) {\n if (!isObjectLike(value)) {\n return false;\n }\n var tag = baseGetTag(value);\n return tag == errorTag || tag == domExcTag ||\n (typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject(value));\n }\n\n /**\n * Checks if `value` is a finite primitive number.\n *\n * **Note:** This method is based on\n * [`Number.isFinite`](https://mdn.io/Number/isFinite).\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 finite number, else `false`.\n * @example\n *\n * _.isFinite(3);\n * // => true\n *\n * _.isFinite(Number.MIN_VALUE);\n * // => true\n *\n * _.isFinite(Infinity);\n * // => false\n *\n * _.isFinite('3');\n * // => false\n */\n function isFinite(value) {\n return typeof value == 'number' && nativeIsFinite(value);\n }\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 */\n function 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\n /**\n * Checks if `value` is an integer.\n *\n * **Note:** This method is based on\n * [`Number.isInteger`](https://mdn.io/Number/isInteger).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an integer, else `false`.\n * @example\n *\n * _.isInteger(3);\n * // => true\n *\n * _.isInteger(Number.MIN_VALUE);\n * // => false\n *\n * _.isInteger(Infinity);\n * // => false\n *\n * _.isInteger('3');\n * // => false\n */\n function isInteger(value) {\n return typeof value == 'number' && value == toInteger(value);\n }\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 */\n function isLength(value) {\n return typeof value == 'number' &&\n value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;\n }\n\n /**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\n function isObject(value) {\n var type = typeof value;\n return value != null && (type == 'object' || type == 'function');\n }\n\n /**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\n function isObjectLike(value) {\n return value != null && typeof value == 'object';\n }\n\n /**\n * Checks if `value` is classified as a `Map` object.\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 map, else `false`.\n * @example\n *\n * _.isMap(new Map);\n * // => true\n *\n * _.isMap(new WeakMap);\n * // => false\n */\n var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap;\n\n /**\n * Performs a partial deep comparison between `object` and `source` to\n * determine if `object` contains equivalent property values.\n *\n * **Note:** This method is equivalent to `_.matches` when `source` is\n * partially applied.\n *\n * Partial comparisons will match empty array and empty object `source`\n * values against any array or object value, respectively. See `_.isEqual`\n * for a list of supported value comparisons.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {Object} object The object to inspect.\n * @param {Object} source The object of property values to match.\n * @returns {boolean} Returns `true` if `object` is a match, else `false`.\n * @example\n *\n * var object = { 'a': 1, 'b': 2 };\n *\n * _.isMatch(object, { 'b': 2 });\n * // => true\n *\n * _.isMatch(object, { 'b': 1 });\n * // => false\n */\n function isMatch(object, source) {\n return object === source || baseIsMatch(object, source, getMatchData(source));\n }\n\n /**\n * This method is like `_.isMatch` except that it accepts `customizer` which\n * is invoked to compare values. If `customizer` returns `undefined`, comparisons\n * are handled by the method instead. The `customizer` is invoked with five\n * arguments: (objValue, srcValue, index|key, object, source).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {Object} object The object to inspect.\n * @param {Object} source The object of property values to match.\n * @param {Function} [customizer] The function to customize comparisons.\n * @returns {boolean} Returns `true` if `object` is a match, else `false`.\n * @example\n *\n * function isGreeting(value) {\n * return /^h(?:i|ello)$/.test(value);\n * }\n *\n * function customizer(objValue, srcValue) {\n * if (isGreeting(objValue) && isGreeting(srcValue)) {\n * return true;\n * }\n * }\n *\n * var object = { 'greeting': 'hello' };\n * var source = { 'greeting': 'hi' };\n *\n * _.isMatchWith(object, source, customizer);\n * // => true\n */\n function isMatchWith(object, source, customizer) {\n customizer = typeof customizer == 'function' ? customizer : undefined;\n return baseIsMatch(object, source, getMatchData(source), customizer);\n }\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 */\n function 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\n /**\n * Checks if `value` is a pristine native function.\n *\n * **Note:** This method can't reliably detect native functions in the presence\n * of the core-js package because core-js circumvents this kind of detection.\n * Despite multiple requests, the core-js maintainer has made it clear: any\n * attempt to fix the detection will be obstructed. As a result, we're left\n * with little choice but to throw an error. Unfortunately, this also affects\n * packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill),\n * which rely on core-js.\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 native function,\n * else `false`.\n * @example\n *\n * _.isNative(Array.prototype.push);\n * // => true\n *\n * _.isNative(_);\n * // => false\n */\n function isNative(value) {\n if (isMaskable(value)) {\n throw new Error(CORE_ERROR_TEXT);\n }\n return baseIsNative(value);\n }\n\n /**\n * Checks if `value` is `null`.\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 `null`, else `false`.\n * @example\n *\n * _.isNull(null);\n * // => true\n *\n * _.isNull(void 0);\n * // => false\n */\n function isNull(value) {\n return value === null;\n }\n\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 */\n function isNil(value) {\n return value == null;\n }\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 */\n function isNumber(value) {\n return typeof value == 'number' ||\n (isObjectLike(value) && baseGetTag(value) == numberTag);\n }\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 */\n function 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\n /**\n * Checks if `value` is classified as a `RegExp` 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 regexp, else `false`.\n * @example\n *\n * _.isRegExp(/abc/);\n * // => true\n *\n * _.isRegExp('/abc/');\n * // => false\n */\n var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp;\n\n /**\n * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754\n * double precision number which isn't the result of a rounded unsafe integer.\n *\n * **Note:** This method is based on\n * [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger).\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 safe integer, else `false`.\n * @example\n *\n * _.isSafeInteger(3);\n * // => true\n *\n * _.isSafeInteger(Number.MIN_VALUE);\n * // => false\n *\n * _.isSafeInteger(Infinity);\n * // => false\n *\n * _.isSafeInteger('3');\n * // => false\n */\n function isSafeInteger(value) {\n return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER;\n }\n\n /**\n * Checks if `value` is classified as a `Set` object.\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 set, else `false`.\n * @example\n *\n * _.isSet(new Set);\n * // => true\n *\n * _.isSet(new WeakSet);\n * // => false\n */\n var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet;\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 */\n function isString(value) {\n return typeof value == 'string' ||\n (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag);\n }\n\n /**\n * Checks if `value` is classified as a `Symbol` primitive or object.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.\n * @example\n *\n * _.isSymbol(Symbol.iterator);\n * // => true\n *\n * _.isSymbol('abc');\n * // => false\n */\n function isSymbol(value) {\n return typeof value == 'symbol' ||\n (isObjectLike(value) && baseGetTag(value) == symbolTag);\n }\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 */\n var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;\n\n /**\n * Checks if `value` is `undefined`.\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 `undefined`, else `false`.\n * @example\n *\n * _.isUndefined(void 0);\n * // => true\n *\n * _.isUndefined(null);\n * // => false\n */\n function isUndefined(value) {\n return value === undefined;\n }\n\n /**\n * Checks if `value` is classified as a `WeakMap` object.\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 weak map, else `false`.\n * @example\n *\n * _.isWeakMap(new WeakMap);\n * // => true\n *\n * _.isWeakMap(new Map);\n * // => false\n */\n function isWeakMap(value) {\n return isObjectLike(value) && getTag(value) == weakMapTag;\n }\n\n /**\n * Checks if `value` is classified as a `WeakSet` object.\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 weak set, else `false`.\n * @example\n *\n * _.isWeakSet(new WeakSet);\n * // => true\n *\n * _.isWeakSet(new Set);\n * // => false\n */\n function isWeakSet(value) {\n return isObjectLike(value) && baseGetTag(value) == weakSetTag;\n }\n\n /**\n * Checks if `value` is less than `other`.\n *\n * @static\n * @memberOf _\n * @since 3.9.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 `value` is less than `other`,\n * else `false`.\n * @see _.gt\n * @example\n *\n * _.lt(1, 3);\n * // => true\n *\n * _.lt(3, 3);\n * // => false\n *\n * _.lt(3, 1);\n * // => false\n */\n var lt = createRelationalOperation(baseLt);\n\n /**\n * Checks if `value` is less than or equal to `other`.\n *\n * @static\n * @memberOf _\n * @since 3.9.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 `value` is less than or equal to\n * `other`, else `false`.\n * @see _.gte\n * @example\n *\n * _.lte(1, 3);\n * // => true\n *\n * _.lte(3, 3);\n * // => true\n *\n * _.lte(3, 1);\n * // => false\n */\n var lte = createRelationalOperation(function(value, other) {\n return value <= other;\n });\n\n /**\n * Converts `value` to an array.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {Array} Returns the converted array.\n * @example\n *\n * _.toArray({ 'a': 1, 'b': 2 });\n * // => [1, 2]\n *\n * _.toArray('abc');\n * // => ['a', 'b', 'c']\n *\n * _.toArray(1);\n * // => []\n *\n * _.toArray(null);\n * // => []\n */\n function toArray(value) {\n if (!value) {\n return [];\n }\n if (isArrayLike(value)) {\n return isString(value) ? stringToArray(value) : copyArray(value);\n }\n if (symIterator && value[symIterator]) {\n return iteratorToArray(value[symIterator]());\n }\n var tag = getTag(value),\n func = tag == mapTag ? mapToArray : (tag == setTag ? setToArray : values);\n\n return func(value);\n }\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 */\n function 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\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 */\n function toInteger(value) {\n var result = toFinite(value),\n remainder = result % 1;\n\n return result === result ? (remainder ? result - remainder : result) : 0;\n }\n\n /**\n * Converts `value` to an integer suitable for use as the length of an\n * array-like object.\n *\n * **Note:** This method is 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 convert.\n * @returns {number} Returns the converted integer.\n * @example\n *\n * _.toLength(3.2);\n * // => 3\n *\n * _.toLength(Number.MIN_VALUE);\n * // => 0\n *\n * _.toLength(Infinity);\n * // => 4294967295\n *\n * _.toLength('3.2');\n * // => 3\n */\n function toLength(value) {\n return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0;\n }\n\n /**\n * Converts `value` to a number.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to process.\n * @returns {number} Returns the number.\n * @example\n *\n * _.toNumber(3.2);\n * // => 3.2\n *\n * _.toNumber(Number.MIN_VALUE);\n * // => 5e-324\n *\n * _.toNumber(Infinity);\n * // => Infinity\n *\n * _.toNumber('3.2');\n * // => 3.2\n */\n function 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\n /**\n * Converts `value` to a plain object flattening inherited enumerable string\n * keyed properties of `value` to own properties of the plain object.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {Object} Returns the converted plain object.\n * @example\n *\n * function Foo() {\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.assign({ 'a': 1 }, new Foo);\n * // => { 'a': 1, 'b': 2 }\n *\n * _.assign({ 'a': 1 }, _.toPlainObject(new Foo));\n * // => { 'a': 1, 'b': 2, 'c': 3 }\n */\n function toPlainObject(value) {\n return copyObject(value, keysIn(value));\n }\n\n /**\n * Converts `value` to a safe integer. A safe integer can be compared and\n * represented correctly.\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 * _.toSafeInteger(3.2);\n * // => 3\n *\n * _.toSafeInteger(Number.MIN_VALUE);\n * // => 0\n *\n * _.toSafeInteger(Infinity);\n * // => 9007199254740991\n *\n * _.toSafeInteger('3.2');\n * // => 3\n */\n function toSafeInteger(value) {\n return value\n ? baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER)\n : (value === 0 ? value : 0);\n }\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 */\n function toString(value) {\n return value == null ? '' : baseToString(value);\n }\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Assigns own enumerable string keyed properties of source objects to the\n * destination object. Source objects are applied from left to right.\n * Subsequent sources overwrite property assignments of previous sources.\n *\n * **Note:** This method mutates `object` and is loosely based on\n * [`Object.assign`](https://mdn.io/Object/assign).\n *\n * @static\n * @memberOf _\n * @since 0.10.0\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} [sources] The source objects.\n * @returns {Object} Returns `object`.\n * @see _.assignIn\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * }\n *\n * function Bar() {\n * this.c = 3;\n * }\n *\n * Foo.prototype.b = 2;\n * Bar.prototype.d = 4;\n *\n * _.assign({ 'a': 0 }, new Foo, new Bar);\n * // => { 'a': 1, 'c': 3 }\n */\n var assign = createAssigner(function(object, source) {\n if (isPrototype(source) || isArrayLike(source)) {\n copyObject(source, keys(source), object);\n return;\n }\n for (var key in source) {\n if (hasOwnProperty.call(source, key)) {\n assignValue(object, key, source[key]);\n }\n }\n });\n\n /**\n * This method is like `_.assign` except that it iterates over own and\n * inherited source properties.\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @alias extend\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} [sources] The source objects.\n * @returns {Object} Returns `object`.\n * @see _.assign\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * }\n *\n * function Bar() {\n * this.c = 3;\n * }\n *\n * Foo.prototype.b = 2;\n * Bar.prototype.d = 4;\n *\n * _.assignIn({ 'a': 0 }, new Foo, new Bar);\n * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 }\n */\n var assignIn = createAssigner(function(object, source) {\n copyObject(source, keysIn(source), object);\n });\n\n /**\n * This method is like `_.assignIn` except that it accepts `customizer`\n * which is invoked to produce the assigned values. If `customizer` returns\n * `undefined`, assignment is handled by the method instead. The `customizer`\n * is invoked with five arguments: (objValue, srcValue, key, object, source).\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @alias extendWith\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} sources The source objects.\n * @param {Function} [customizer] The function to customize assigned values.\n * @returns {Object} Returns `object`.\n * @see _.assignWith\n * @example\n *\n * function customizer(objValue, srcValue) {\n * return _.isUndefined(objValue) ? srcValue : objValue;\n * }\n *\n * var defaults = _.partialRight(_.assignInWith, customizer);\n *\n * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });\n * // => { 'a': 1, 'b': 2 }\n */\n var assignInWith = createAssigner(function(object, source, srcIndex, customizer) {\n copyObject(source, keysIn(source), object, customizer);\n });\n\n /**\n * This method is like `_.assign` except that it accepts `customizer`\n * which is invoked to produce the assigned values. If `customizer` returns\n * `undefined`, assignment is handled by the method instead. The `customizer`\n * is invoked with five arguments: (objValue, srcValue, key, object, source).\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} sources The source objects.\n * @param {Function} [customizer] The function to customize assigned values.\n * @returns {Object} Returns `object`.\n * @see _.assignInWith\n * @example\n *\n * function customizer(objValue, srcValue) {\n * return _.isUndefined(objValue) ? srcValue : objValue;\n * }\n *\n * var defaults = _.partialRight(_.assignWith, customizer);\n *\n * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });\n * // => { 'a': 1, 'b': 2 }\n */\n var assignWith = createAssigner(function(object, source, srcIndex, customizer) {\n copyObject(source, keys(source), object, customizer);\n });\n\n /**\n * Creates an array of values corresponding to `paths` of `object`.\n *\n * @static\n * @memberOf _\n * @since 1.0.0\n * @category Object\n * @param {Object} object The object to iterate over.\n * @param {...(string|string[])} [paths] The property paths to pick.\n * @returns {Array} Returns the picked values.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };\n *\n * _.at(object, ['a[0].b.c', 'a[1]']);\n * // => [3, 4]\n */\n var at = flatRest(baseAt);\n\n /**\n * Creates an object that inherits from the `prototype` object. If a\n * `properties` object is given, its own enumerable string keyed properties\n * are assigned to the created object.\n *\n * @static\n * @memberOf _\n * @since 2.3.0\n * @category Object\n * @param {Object} prototype The object to inherit from.\n * @param {Object} [properties] The properties to assign to the object.\n * @returns {Object} Returns the new object.\n * @example\n *\n * function Shape() {\n * this.x = 0;\n * this.y = 0;\n * }\n *\n * function Circle() {\n * Shape.call(this);\n * }\n *\n * Circle.prototype = _.create(Shape.prototype, {\n * 'constructor': Circle\n * });\n *\n * var circle = new Circle;\n * circle instanceof Circle;\n * // => true\n *\n * circle instanceof Shape;\n * // => true\n */\n function create(prototype, properties) {\n var result = baseCreate(prototype);\n return properties == null ? result : baseAssign(result, properties);\n }\n\n /**\n * Assigns own and inherited enumerable string keyed properties of source\n * objects to the destination object for all destination properties that\n * resolve to `undefined`. Source objects are applied from left to right.\n * Once a property is set, additional values of the same property are ignored.\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} [sources] The source objects.\n * @returns {Object} Returns `object`.\n * @see _.defaultsDeep\n * @example\n *\n * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });\n * // => { 'a': 1, 'b': 2 }\n */\n var defaults = baseRest(function(object, sources) {\n object = Object(object);\n\n var index = -1;\n var length = sources.length;\n var guard = length > 2 ? sources[2] : undefined;\n\n if (guard && isIterateeCall(sources[0], sources[1], guard)) {\n length = 1;\n }\n\n while (++index < length) {\n var source = sources[index];\n var props = keysIn(source);\n var propsIndex = -1;\n var propsLength = props.length;\n\n while (++propsIndex < propsLength) {\n var key = props[propsIndex];\n var value = object[key];\n\n if (value === undefined ||\n (eq(value, objectProto[key]) && !hasOwnProperty.call(object, key))) {\n object[key] = source[key];\n }\n }\n }\n\n return object;\n });\n\n /**\n * This method is like `_.defaults` except that it recursively assigns\n * default properties.\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 3.10.0\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} [sources] The source objects.\n * @returns {Object} Returns `object`.\n * @see _.defaults\n * @example\n *\n * _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } });\n * // => { 'a': { 'b': 2, 'c': 3 } }\n */\n var defaultsDeep = baseRest(function(args) {\n args.push(undefined, customDefaultsMerge);\n return apply(mergeWith, undefined, args);\n });\n\n /**\n * This method is like `_.find` except that it returns the key 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 Object\n * @param {Object} object The object to inspect.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {string|undefined} Returns the key of the matched element,\n * else `undefined`.\n * @example\n *\n * var users = {\n * 'barney': { 'age': 36, 'active': true },\n * 'fred': { 'age': 40, 'active': false },\n * 'pebbles': { 'age': 1, 'active': true }\n * };\n *\n * _.findKey(users, function(o) { return o.age < 40; });\n * // => 'barney' (iteration order is not guaranteed)\n *\n * // The `_.matches` iteratee shorthand.\n * _.findKey(users, { 'age': 1, 'active': true });\n * // => 'pebbles'\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.findKey(users, ['active', false]);\n * // => 'fred'\n *\n * // The `_.property` iteratee shorthand.\n * _.findKey(users, 'active');\n * // => 'barney'\n */\n function findKey(object, predicate) {\n return baseFindKey(object, getIteratee(predicate, 3), baseForOwn);\n }\n\n /**\n * This method is like `_.findKey` except that it iterates over elements of\n * a collection in the opposite order.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @category Object\n * @param {Object} object The object to inspect.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {string|undefined} Returns the key of the matched element,\n * else `undefined`.\n * @example\n *\n * var users = {\n * 'barney': { 'age': 36, 'active': true },\n * 'fred': { 'age': 40, 'active': false },\n * 'pebbles': { 'age': 1, 'active': true }\n * };\n *\n * _.findLastKey(users, function(o) { return o.age < 40; });\n * // => returns 'pebbles' assuming `_.findKey` returns 'barney'\n *\n * // The `_.matches` iteratee shorthand.\n * _.findLastKey(users, { 'age': 36, 'active': true });\n * // => 'barney'\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.findLastKey(users, ['active', false]);\n * // => 'fred'\n *\n * // The `_.property` iteratee shorthand.\n * _.findLastKey(users, 'active');\n * // => 'pebbles'\n */\n function findLastKey(object, predicate) {\n return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight);\n }\n\n /**\n * Iterates over own and inherited enumerable string keyed properties of an\n * object and invokes `iteratee` for each property. The iteratee is invoked\n * with three arguments: (value, key, object). Iteratee functions may exit\n * iteration early by explicitly returning `false`.\n *\n * @static\n * @memberOf _\n * @since 0.3.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 `object`.\n * @see _.forInRight\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.forIn(new Foo, function(value, key) {\n * console.log(key);\n * });\n * // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed).\n */\n function forIn(object, iteratee) {\n return object == null\n ? object\n : baseFor(object, getIteratee(iteratee, 3), keysIn);\n }\n\n /**\n * This method is like `_.forIn` except that it iterates over properties of\n * `object` in the opposite order.\n *\n * @static\n * @memberOf _\n * @since 2.0.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 `object`.\n * @see _.forIn\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.forInRight(new Foo, function(value, key) {\n * console.log(key);\n * });\n * // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'.\n */\n function forInRight(object, iteratee) {\n return object == null\n ? object\n : baseForRight(object, getIteratee(iteratee, 3), keysIn);\n }\n\n /**\n * Iterates over own enumerable string keyed properties of an object and\n * invokes `iteratee` for each property. The iteratee is invoked with three\n * arguments: (value, key, object). Iteratee functions may exit iteration\n * early by explicitly returning `false`.\n *\n * @static\n * @memberOf _\n * @since 0.3.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 `object`.\n * @see _.forOwnRight\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.forOwn(new Foo, function(value, key) {\n * console.log(key);\n * });\n * // => Logs 'a' then 'b' (iteration order is not guaranteed).\n */\n function forOwn(object, iteratee) {\n return object && baseForOwn(object, getIteratee(iteratee, 3));\n }\n\n /**\n * This method is like `_.forOwn` except that it iterates over properties of\n * `object` in the opposite order.\n *\n * @static\n * @memberOf _\n * @since 2.0.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 `object`.\n * @see _.forOwn\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.forOwnRight(new Foo, function(value, key) {\n * console.log(key);\n * });\n * // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'.\n */\n function forOwnRight(object, iteratee) {\n return object && baseForOwnRight(object, getIteratee(iteratee, 3));\n }\n\n /**\n * Creates an array of function property names from own enumerable properties\n * of `object`.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to inspect.\n * @returns {Array} Returns the function names.\n * @see _.functionsIn\n * @example\n *\n * function Foo() {\n * this.a = _.constant('a');\n * this.b = _.constant('b');\n * }\n *\n * Foo.prototype.c = _.constant('c');\n *\n * _.functions(new Foo);\n * // => ['a', 'b']\n */\n function functions(object) {\n return object == null ? [] : baseFunctions(object, keys(object));\n }\n\n /**\n * Creates an array of function property names from own and inherited\n * enumerable properties of `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The object to inspect.\n * @returns {Array} Returns the function names.\n * @see _.functions\n * @example\n *\n * function Foo() {\n * this.a = _.constant('a');\n * this.b = _.constant('b');\n * }\n *\n * Foo.prototype.c = _.constant('c');\n *\n * _.functionsIn(new Foo);\n * // => ['a', 'b', 'c']\n */\n function functionsIn(object) {\n return object == null ? [] : baseFunctions(object, keysIn(object));\n }\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 */\n function get(object, path, defaultValue) {\n var result = object == null ? undefined : baseGet(object, path);\n return result === undefined ? defaultValue : result;\n }\n\n /**\n * Checks if `path` is a direct property of `object`.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\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 = { 'a': { 'b': 2 } };\n * var other = _.create({ 'a': _.create({ 'b': 2 }) });\n *\n * _.has(object, 'a');\n * // => true\n *\n * _.has(object, 'a.b');\n * // => true\n *\n * _.has(object, ['a', 'b']);\n * // => true\n *\n * _.has(other, 'a');\n * // => false\n */\n function has(object, path) {\n return object != null && hasPath(object, path, baseHas);\n }\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 */\n function hasIn(object, path) {\n return object != null && hasPath(object, path, baseHasIn);\n }\n\n /**\n * Creates an object composed of the inverted keys and values of `object`.\n * If `object` contains duplicate values, subsequent values overwrite\n * property assignments of previous values.\n *\n * @static\n * @memberOf _\n * @since 0.7.0\n * @category Object\n * @param {Object} object The object to invert.\n * @returns {Object} Returns the new inverted object.\n * @example\n *\n * var object = { 'a': 1, 'b': 2, 'c': 1 };\n *\n * _.invert(object);\n * // => { '1': 'c', '2': 'b' }\n */\n var invert = createInverter(function(result, value, key) {\n if (value != null &&\n typeof value.toString != 'function') {\n value = nativeObjectToString.call(value);\n }\n\n result[value] = key;\n }, constant(identity));\n\n /**\n * This method is like `_.invert` except that the inverted object is generated\n * from the results of running each element of `object` thru `iteratee`. The\n * corresponding inverted value of each inverted key is an array of keys\n * responsible for generating the inverted value. The iteratee is invoked\n * with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 4.1.0\n * @category Object\n * @param {Object} object The object to invert.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {Object} Returns the new inverted object.\n * @example\n *\n * var object = { 'a': 1, 'b': 2, 'c': 1 };\n *\n * _.invertBy(object);\n * // => { '1': ['a', 'c'], '2': ['b'] }\n *\n * _.invertBy(object, function(value) {\n * return 'group' + value;\n * });\n * // => { 'group1': ['a', 'c'], 'group2': ['b'] }\n */\n var invertBy = createInverter(function(result, value, key) {\n if (value != null &&\n typeof value.toString != 'function') {\n value = nativeObjectToString.call(value);\n }\n\n if (hasOwnProperty.call(result, value)) {\n result[value].push(key);\n } else {\n result[value] = [key];\n }\n }, getIteratee);\n\n /**\n * Invokes the method at `path` 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 of the method to invoke.\n * @param {...*} [args] The arguments to invoke the method with.\n * @returns {*} Returns the result of the invoked method.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] };\n *\n * _.invoke(object, 'a[0].b.c.slice', 1, 3);\n * // => [2, 3]\n */\n var invoke = baseRest(baseInvoke);\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 */\n function keys(object) {\n return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);\n }\n\n /**\n * Creates an array of the own and inherited enumerable property names of `object`.\n *\n * **Note:** Non-object values are coerced to objects.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.keysIn(new Foo);\n * // => ['a', 'b', 'c'] (iteration order is not guaranteed)\n */\n function keysIn(object) {\n return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);\n }\n\n /**\n * The opposite of `_.mapValues`; this method creates an object with the\n * same values as `object` and keys generated by running each own enumerable\n * string keyed property of `object` thru `iteratee`. The iteratee is invoked\n * with three arguments: (value, key, object).\n *\n * @static\n * @memberOf _\n * @since 3.8.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 _.mapValues\n * @example\n *\n * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) {\n * return key + value;\n * });\n * // => { 'a1': 1, 'b2': 2 }\n */\n function mapKeys(object, iteratee) {\n var result = {};\n iteratee = getIteratee(iteratee, 3);\n\n baseForOwn(object, function(value, key, object) {\n baseAssignValue(result, iteratee(value, key, object), value);\n });\n return result;\n }\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 */\n function mapValues(object, iteratee) {\n var result = {};\n iteratee = getIteratee(iteratee, 3);\n\n baseForOwn(object, function(value, key, object) {\n baseAssignValue(result, key, iteratee(value, key, object));\n });\n return result;\n }\n\n /**\n * This method is like `_.assign` except that it recursively merges own and\n * inherited enumerable string keyed properties of source objects into the\n * destination object. Source properties that resolve to `undefined` are\n * skipped if a destination value exists. Array and plain object properties\n * are merged recursively. Other objects and value types are overridden by\n * assignment. Source objects are applied from left to right. Subsequent\n * sources overwrite property assignments of previous sources.\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 0.5.0\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} [sources] The source objects.\n * @returns {Object} Returns `object`.\n * @example\n *\n * var object = {\n * 'a': [{ 'b': 2 }, { 'd': 4 }]\n * };\n *\n * var other = {\n * 'a': [{ 'c': 3 }, { 'e': 5 }]\n * };\n *\n * _.merge(object, other);\n * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }\n */\n var merge = createAssigner(function(object, source, srcIndex) {\n baseMerge(object, source, srcIndex);\n });\n\n /**\n * This method is like `_.merge` except that it accepts `customizer` which\n * is invoked to produce the merged values of the destination and source\n * properties. If `customizer` returns `undefined`, merging is handled by the\n * method instead. The `customizer` is invoked with six arguments:\n * (objValue, srcValue, key, object, source, stack).\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} sources The source objects.\n * @param {Function} customizer The function to customize assigned values.\n * @returns {Object} Returns `object`.\n * @example\n *\n * function customizer(objValue, srcValue) {\n * if (_.isArray(objValue)) {\n * return objValue.concat(srcValue);\n * }\n * }\n *\n * var object = { 'a': [1], 'b': [2] };\n * var other = { 'a': [3], 'b': [4] };\n *\n * _.mergeWith(object, other, customizer);\n * // => { 'a': [1, 3], 'b': [2, 4] }\n */\n var mergeWith = createAssigner(function(object, source, srcIndex, customizer) {\n baseMerge(object, source, srcIndex, customizer);\n });\n\n /**\n * The opposite of `_.pick`; this method creates an object composed of the\n * own and inherited enumerable property paths of `object` that are not omitted.\n *\n * **Note:** This method is considerably slower than `_.pick`.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The source object.\n * @param {...(string|string[])} [paths] The property paths to omit.\n * @returns {Object} Returns the new object.\n * @example\n *\n * var object = { 'a': 1, 'b': '2', 'c': 3 };\n *\n * _.omit(object, ['a', 'c']);\n * // => { 'b': '2' }\n */\n var omit = flatRest(function(object, paths) {\n var result = {};\n if (object == null) {\n return result;\n }\n var isDeep = false;\n paths = arrayMap(paths, function(path) {\n path = castPath(path, object);\n isDeep || (isDeep = path.length > 1);\n return path;\n });\n copyObject(object, getAllKeysIn(object), result);\n if (isDeep) {\n result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone);\n }\n var length = paths.length;\n while (length--) {\n baseUnset(result, paths[length]);\n }\n return result;\n });\n\n /**\n * The opposite of `_.pickBy`; this method creates an object composed of\n * the own and inherited enumerable string keyed properties of `object` that\n * `predicate` doesn't return truthy for. The predicate is invoked with two\n * arguments: (value, key).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The source object.\n * @param {Function} [predicate=_.identity] The function invoked per property.\n * @returns {Object} Returns the new object.\n * @example\n *\n * var object = { 'a': 1, 'b': '2', 'c': 3 };\n *\n * _.omitBy(object, _.isNumber);\n * // => { 'b': '2' }\n */\n function omitBy(object, predicate) {\n return pickBy(object, negate(getIteratee(predicate)));\n }\n\n /**\n * Creates an object composed of the picked `object` properties.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The source object.\n * @param {...(string|string[])} [paths] The property paths to pick.\n * @returns {Object} Returns the new object.\n * @example\n *\n * var object = { 'a': 1, 'b': '2', 'c': 3 };\n *\n * _.pick(object, ['a', 'c']);\n * // => { 'a': 1, 'c': 3 }\n */\n var pick = flatRest(function(object, paths) {\n return object == null ? {} : basePick(object, paths);\n });\n\n /**\n * Creates an object composed of the `object` properties `predicate` returns\n * truthy for. The predicate is invoked with two arguments: (value, key).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The source object.\n * @param {Function} [predicate=_.identity] The function invoked per property.\n * @returns {Object} Returns the new object.\n * @example\n *\n * var object = { 'a': 1, 'b': '2', 'c': 3 };\n *\n * _.pickBy(object, _.isNumber);\n * // => { 'a': 1, 'c': 3 }\n */\n function pickBy(object, predicate) {\n if (object == null) {\n return {};\n }\n var props = arrayMap(getAllKeysIn(object), function(prop) {\n return [prop];\n });\n predicate = getIteratee(predicate);\n return basePickBy(object, props, function(value, path) {\n return predicate(value, path[0]);\n });\n }\n\n /**\n * This method is like `_.get` except that if the resolved value is a\n * function it's invoked with the `this` binding of its parent object and\n * its result is returned.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @param {Array|string} path The path of the property to resolve.\n * @param {*} [defaultValue] The value returned for `undefined` resolved values.\n * @returns {*} Returns the resolved value.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] };\n *\n * _.result(object, 'a[0].b.c1');\n * // => 3\n *\n * _.result(object, 'a[0].b.c2');\n * // => 4\n *\n * _.result(object, 'a[0].b.c3', 'default');\n * // => 'default'\n *\n * _.result(object, 'a[0].b.c3', _.constant('default'));\n * // => 'default'\n */\n function result(object, path, defaultValue) {\n path = castPath(path, object);\n\n var index = -1,\n length = path.length;\n\n // Ensure the loop is entered when path is empty.\n if (!length) {\n length = 1;\n object = undefined;\n }\n while (++index < length) {\n var value = object == null ? undefined : object[toKey(path[index])];\n if (value === undefined) {\n index = length;\n value = defaultValue;\n }\n object = isFunction(value) ? value.call(object) : value;\n }\n return object;\n }\n\n /**\n * Sets the value at `path` of `object`. If a portion of `path` doesn't exist,\n * it's created. Arrays are created for missing index properties while objects\n * are created for all other missing properties. Use `_.setWith` to customize\n * `path` creation.\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 3.7.0\n * @category Object\n * @param {Object} object The object to modify.\n * @param {Array|string} path The path of the property to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns `object`.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': 3 } }] };\n *\n * _.set(object, 'a[0].b.c', 4);\n * console.log(object.a[0].b.c);\n * // => 4\n *\n * _.set(object, ['x', '0', 'y', 'z'], 5);\n * console.log(object.x[0].y.z);\n * // => 5\n */\n function set(object, path, value) {\n return object == null ? object : baseSet(object, path, value);\n }\n\n /**\n * This method is like `_.set` except that it accepts `customizer` which is\n * invoked to produce the objects of `path`. If `customizer` returns `undefined`\n * path creation is handled by the method instead. The `customizer` is invoked\n * with three arguments: (nsValue, key, nsObject).\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The object to modify.\n * @param {Array|string} path The path of the property to set.\n * @param {*} value The value to set.\n * @param {Function} [customizer] The function to customize assigned values.\n * @returns {Object} Returns `object`.\n * @example\n *\n * var object = {};\n *\n * _.setWith(object, '[0][1]', 'a', Object);\n * // => { '0': { '1': 'a' } }\n */\n function setWith(object, path, value, customizer) {\n customizer = typeof customizer == 'function' ? customizer : undefined;\n return object == null ? object : baseSet(object, path, value, customizer);\n }\n\n /**\n * Creates an array of own enumerable string keyed-value pairs for `object`\n * which can be consumed by `_.fromPairs`. If `object` is a map or set, its\n * entries are returned.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @alias entries\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the key-value pairs.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.toPairs(new Foo);\n * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed)\n */\n var toPairs = createToPairs(keys);\n\n /**\n * Creates an array of own and inherited enumerable string keyed-value pairs\n * for `object` which can be consumed by `_.fromPairs`. If `object` is a map\n * or set, its entries are returned.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @alias entriesIn\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the key-value pairs.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.toPairsIn(new Foo);\n * // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed)\n */\n var toPairsIn = createToPairs(keysIn);\n\n /**\n * An alternative to `_.reduce`; this method transforms `object` to a new\n * `accumulator` object which is the result of running each of its own\n * enumerable string keyed properties thru `iteratee`, with each invocation\n * potentially mutating the `accumulator` object. If `accumulator` is not\n * provided, a new object with the same `[[Prototype]]` will be used. The\n * iteratee is invoked with four arguments: (accumulator, value, key, object).\n * Iteratee functions may exit iteration early by explicitly returning `false`.\n *\n * @static\n * @memberOf _\n * @since 1.3.0\n * @category Object\n * @param {Object} object The object to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @param {*} [accumulator] The custom accumulator value.\n * @returns {*} Returns the accumulated value.\n * @example\n *\n * _.transform([2, 3, 4], function(result, n) {\n * result.push(n *= n);\n * return n % 2 == 0;\n * }, []);\n * // => [4, 9]\n *\n * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {\n * (result[value] || (result[value] = [])).push(key);\n * }, {});\n * // => { '1': ['a', 'c'], '2': ['b'] }\n */\n function transform(object, iteratee, accumulator) {\n var isArr = isArray(object),\n isArrLike = isArr || isBuffer(object) || isTypedArray(object);\n\n iteratee = getIteratee(iteratee, 4);\n if (accumulator == null) {\n var Ctor = object && object.constructor;\n if (isArrLike) {\n accumulator = isArr ? new Ctor : [];\n }\n else if (isObject(object)) {\n accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {};\n }\n else {\n accumulator = {};\n }\n }\n (isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object) {\n return iteratee(accumulator, value, index, object);\n });\n return accumulator;\n }\n\n /**\n * Removes the property at `path` of `object`.\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The object to modify.\n * @param {Array|string} path The path of the property to unset.\n * @returns {boolean} Returns `true` if the property is deleted, else `false`.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': 7 } }] };\n * _.unset(object, 'a[0].b.c');\n * // => true\n *\n * console.log(object);\n * // => { 'a': [{ 'b': {} }] };\n *\n * _.unset(object, ['a', '0', 'b', 'c']);\n * // => true\n *\n * console.log(object);\n * // => { 'a': [{ 'b': {} }] };\n */\n function unset(object, path) {\n return object == null ? true : baseUnset(object, path);\n }\n\n /**\n * This method is like `_.set` except that accepts `updater` to produce the\n * value to set. Use `_.updateWith` to customize `path` creation. The `updater`\n * is invoked with one argument: (value).\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 4.6.0\n * @category Object\n * @param {Object} object The object to modify.\n * @param {Array|string} path The path of the property to set.\n * @param {Function} updater The function to produce the updated value.\n * @returns {Object} Returns `object`.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': 3 } }] };\n *\n * _.update(object, 'a[0].b.c', function(n) { return n * n; });\n * console.log(object.a[0].b.c);\n * // => 9\n *\n * _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; });\n * console.log(object.x[0].y.z);\n * // => 0\n */\n function update(object, path, updater) {\n return object == null ? object : baseUpdate(object, path, castFunction(updater));\n }\n\n /**\n * This method is like `_.update` except that it accepts `customizer` which is\n * invoked to produce the objects of `path`. If `customizer` returns `undefined`\n * path creation is handled by the method instead. The `customizer` is invoked\n * with three arguments: (nsValue, key, nsObject).\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 4.6.0\n * @category Object\n * @param {Object} object The object to modify.\n * @param {Array|string} path The path of the property to set.\n * @param {Function} updater The function to produce the updated value.\n * @param {Function} [customizer] The function to customize assigned values.\n * @returns {Object} Returns `object`.\n * @example\n *\n * var object = {};\n *\n * _.updateWith(object, '[0][1]', _.constant('a'), Object);\n * // => { '0': { '1': 'a' } }\n */\n function updateWith(object, path, updater, customizer) {\n customizer = typeof customizer == 'function' ? customizer : undefined;\n return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer);\n }\n\n /**\n * Creates an array of the own enumerable string keyed property values of `object`.\n *\n * **Note:** Non-object values are coerced to objects.\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 values.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.values(new Foo);\n * // => [1, 2] (iteration order is not guaranteed)\n *\n * _.values('hi');\n * // => ['h', 'i']\n */\n function values(object) {\n return object == null ? [] : baseValues(object, keys(object));\n }\n\n /**\n * Creates an array of the own and inherited enumerable string keyed property\n * values of `object`.\n *\n * **Note:** Non-object values are coerced to objects.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property values.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.valuesIn(new Foo);\n * // => [1, 2, 3] (iteration order is not guaranteed)\n */\n function valuesIn(object) {\n return object == null ? [] : baseValues(object, keysIn(object));\n }\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Clamps `number` within the inclusive `lower` and `upper` bounds.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Number\n * @param {number} number The number to clamp.\n * @param {number} [lower] The lower bound.\n * @param {number} upper The upper bound.\n * @returns {number} Returns the clamped number.\n * @example\n *\n * _.clamp(-10, -5, 5);\n * // => -5\n *\n * _.clamp(10, -5, 5);\n * // => 5\n */\n function clamp(number, lower, upper) {\n if (upper === undefined) {\n upper = lower;\n lower = undefined;\n }\n if (upper !== undefined) {\n upper = toNumber(upper);\n upper = upper === upper ? upper : 0;\n }\n if (lower !== undefined) {\n lower = toNumber(lower);\n lower = lower === lower ? lower : 0;\n }\n return baseClamp(toNumber(number), lower, upper);\n }\n\n /**\n * Checks if `n` is between `start` and up to, but not including, `end`. If\n * `end` is not specified, it's set to `start` with `start` then set to `0`.\n * If `start` is greater than `end` the params are swapped to support\n * negative ranges.\n *\n * @static\n * @memberOf _\n * @since 3.3.0\n * @category Number\n * @param {number} number The number to check.\n * @param {number} [start=0] The start of the range.\n * @param {number} end The end of the range.\n * @returns {boolean} Returns `true` if `number` is in the range, else `false`.\n * @see _.range, _.rangeRight\n * @example\n *\n * _.inRange(3, 2, 4);\n * // => true\n *\n * _.inRange(4, 8);\n * // => true\n *\n * _.inRange(4, 2);\n * // => false\n *\n * _.inRange(2, 2);\n * // => false\n *\n * _.inRange(1.2, 2);\n * // => true\n *\n * _.inRange(5.2, 4);\n * // => false\n *\n * _.inRange(-3, -2, -6);\n * // => true\n */\n function inRange(number, start, end) {\n start = toFinite(start);\n if (end === undefined) {\n end = start;\n start = 0;\n } else {\n end = toFinite(end);\n }\n number = toNumber(number);\n return baseInRange(number, start, end);\n }\n\n /**\n * Produces a random number between the inclusive `lower` and `upper` bounds.\n * If only one argument is provided a number between `0` and the given number\n * is returned. If `floating` is `true`, or either `lower` or `upper` are\n * floats, a floating-point number is returned instead of an integer.\n *\n * **Note:** JavaScript follows the IEEE-754 standard for resolving\n * floating-point values which can produce unexpected results.\n *\n * @static\n * @memberOf _\n * @since 0.7.0\n * @category Number\n * @param {number} [lower=0] The lower bound.\n * @param {number} [upper=1] The upper bound.\n * @param {boolean} [floating] Specify returning a floating-point number.\n * @returns {number} Returns the random number.\n * @example\n *\n * _.random(0, 5);\n * // => an integer between 0 and 5\n *\n * _.random(5);\n * // => also an integer between 0 and 5\n *\n * _.random(5, true);\n * // => a floating-point number between 0 and 5\n *\n * _.random(1.2, 5.2);\n * // => a floating-point number between 1.2 and 5.2\n */\n function random(lower, upper, floating) {\n if (floating && typeof floating != 'boolean' && isIterateeCall(lower, upper, floating)) {\n upper = floating = undefined;\n }\n if (floating === undefined) {\n if (typeof upper == 'boolean') {\n floating = upper;\n upper = undefined;\n }\n else if (typeof lower == 'boolean') {\n floating = lower;\n lower = undefined;\n }\n }\n if (lower === undefined && upper === undefined) {\n lower = 0;\n upper = 1;\n }\n else {\n lower = toFinite(lower);\n if (upper === undefined) {\n upper = lower;\n lower = 0;\n } else {\n upper = toFinite(upper);\n }\n }\n if (lower > upper) {\n var temp = lower;\n lower = upper;\n upper = temp;\n }\n if (floating || lower % 1 || upper % 1) {\n var rand = nativeRandom();\n return nativeMin(lower + (rand * (upper - lower + freeParseFloat('1e-' + ((rand + '').length - 1)))), upper);\n }\n return baseRandom(lower, upper);\n }\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to convert.\n * @returns {string} Returns the camel cased string.\n * @example\n *\n * _.camelCase('Foo Bar');\n * // => 'fooBar'\n *\n * _.camelCase('--foo-bar--');\n * // => 'fooBar'\n *\n * _.camelCase('__FOO_BAR__');\n * // => 'fooBar'\n */\n var camelCase = createCompounder(function(result, word, index) {\n word = word.toLowerCase();\n return result + (index ? capitalize(word) : word);\n });\n\n /**\n * Converts the first character of `string` to upper case and the remaining\n * to lower case.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to capitalize.\n * @returns {string} Returns the capitalized string.\n * @example\n *\n * _.capitalize('FRED');\n * // => 'Fred'\n */\n function capitalize(string) {\n return upperFirst(toString(string).toLowerCase());\n }\n\n /**\n * Deburrs `string` by converting\n * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table)\n * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A)\n * letters to basic Latin letters and removing\n * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to deburr.\n * @returns {string} Returns the deburred string.\n * @example\n *\n * _.deburr('d\u00E9j\u00E0 vu');\n * // => 'deja vu'\n */\n function deburr(string) {\n string = toString(string);\n return string && string.replace(reLatin, deburrLetter).replace(reComboMark, '');\n }\n\n /**\n * Checks if `string` ends with the given target string.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to inspect.\n * @param {string} [target] The string to search for.\n * @param {number} [position=string.length] The position to search up to.\n * @returns {boolean} Returns `true` if `string` ends with `target`,\n * else `false`.\n * @example\n *\n * _.endsWith('abc', 'c');\n * // => true\n *\n * _.endsWith('abc', 'b');\n * // => false\n *\n * _.endsWith('abc', 'b', 2);\n * // => true\n */\n function endsWith(string, target, position) {\n string = toString(string);\n target = baseToString(target);\n\n var length = string.length;\n position = position === undefined\n ? length\n : baseClamp(toInteger(position), 0, length);\n\n var end = position;\n position -= target.length;\n return position >= 0 && string.slice(position, end) == target;\n }\n\n /**\n * Converts the characters \"&\", \"<\", \">\", '\"', and \"'\" in `string` to their\n * corresponding HTML entities.\n *\n * **Note:** No other characters are escaped. To escape additional\n * characters use a third-party library like [_he_](https://mths.be/he).\n *\n * Though the \">\" character is escaped for symmetry, characters like\n * \">\" and \"/\" don't need escaping in HTML and have no special meaning\n * unless they're part of a tag or unquoted attribute value. See\n * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands)\n * (under \"semi-related fun fact\") for more details.\n *\n * When working with HTML you should always\n * [quote attribute values](http://wonko.com/post/html-escaping) to reduce\n * XSS vectors.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category String\n * @param {string} [string=''] The string to escape.\n * @returns {string} Returns the escaped string.\n * @example\n *\n * _.escape('fred, barney, & pebbles');\n * // => 'fred, barney, & pebbles'\n */\n function escape(string) {\n string = toString(string);\n return (string && reHasUnescapedHtml.test(string))\n ? string.replace(reUnescapedHtml, escapeHtmlChar)\n : string;\n }\n\n /**\n * Escapes the `RegExp` special characters \"^\", \"$\", \"\\\", \".\", \"*\", \"+\",\n * \"?\", \"(\", \")\", \"[\", \"]\", \"{\", \"}\", and \"|\" in `string`.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to escape.\n * @returns {string} Returns the escaped string.\n * @example\n *\n * _.escapeRegExp('[lodash](https://lodash.com/)');\n * // => '\\[lodash\\]\\(https://lodash\\.com/\\)'\n */\n function escapeRegExp(string) {\n string = toString(string);\n return (string && reHasRegExpChar.test(string))\n ? string.replace(reRegExpChar, '\\\\$&')\n : string;\n }\n\n /**\n * Converts `string` to\n * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to convert.\n * @returns {string} Returns the kebab cased string.\n * @example\n *\n * _.kebabCase('Foo Bar');\n * // => 'foo-bar'\n *\n * _.kebabCase('fooBar');\n * // => 'foo-bar'\n *\n * _.kebabCase('__FOO_BAR__');\n * // => 'foo-bar'\n */\n var kebabCase = createCompounder(function(result, word, index) {\n return result + (index ? '-' : '') + word.toLowerCase();\n });\n\n /**\n * Converts `string`, as space separated words, to lower 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 lower cased string.\n * @example\n *\n * _.lowerCase('--Foo-Bar--');\n * // => 'foo bar'\n *\n * _.lowerCase('fooBar');\n * // => 'foo bar'\n *\n * _.lowerCase('__FOO_BAR__');\n * // => 'foo bar'\n */\n var lowerCase = createCompounder(function(result, word, index) {\n return result + (index ? ' ' : '') + word.toLowerCase();\n });\n\n /**\n * Converts the first character of `string` to lower 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 * _.lowerFirst('Fred');\n * // => 'fred'\n *\n * _.lowerFirst('FRED');\n * // => 'fRED'\n */\n var lowerFirst = createCaseFirst('toLowerCase');\n\n /**\n * Pads `string` on the left and right sides if it's shorter than `length`.\n * Padding characters are truncated if they can't be evenly divided by `length`.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to pad.\n * @param {number} [length=0] The padding length.\n * @param {string} [chars=' '] The string used as padding.\n * @returns {string} Returns the padded string.\n * @example\n *\n * _.pad('abc', 8);\n * // => ' abc '\n *\n * _.pad('abc', 8, '_-');\n * // => '_-abc_-_'\n *\n * _.pad('abc', 3);\n * // => 'abc'\n */\n function pad(string, length, chars) {\n string = toString(string);\n length = toInteger(length);\n\n var strLength = length ? stringSize(string) : 0;\n if (!length || strLength >= length) {\n return string;\n }\n var mid = (length - strLength) / 2;\n return (\n createPadding(nativeFloor(mid), chars) +\n string +\n createPadding(nativeCeil(mid), chars)\n );\n }\n\n /**\n * Pads `string` on the right side if it's shorter than `length`. Padding\n * characters are truncated if they exceed `length`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category String\n * @param {string} [string=''] The string to pad.\n * @param {number} [length=0] The padding length.\n * @param {string} [chars=' '] The string used as padding.\n * @returns {string} Returns the padded string.\n * @example\n *\n * _.padEnd('abc', 6);\n * // => 'abc '\n *\n * _.padEnd('abc', 6, '_-');\n * // => 'abc_-_'\n *\n * _.padEnd('abc', 3);\n * // => 'abc'\n */\n function padEnd(string, length, chars) {\n string = toString(string);\n length = toInteger(length);\n\n var strLength = length ? stringSize(string) : 0;\n return (length && strLength < length)\n ? (string + createPadding(length - strLength, chars))\n : string;\n }\n\n /**\n * Pads `string` on the left side if it's shorter than `length`. Padding\n * characters are truncated if they exceed `length`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category String\n * @param {string} [string=''] The string to pad.\n * @param {number} [length=0] The padding length.\n * @param {string} [chars=' '] The string used as padding.\n * @returns {string} Returns the padded string.\n * @example\n *\n * _.padStart('abc', 6);\n * // => ' abc'\n *\n * _.padStart('abc', 6, '_-');\n * // => '_-_abc'\n *\n * _.padStart('abc', 3);\n * // => 'abc'\n */\n function padStart(string, length, chars) {\n string = toString(string);\n length = toInteger(length);\n\n var strLength = length ? stringSize(string) : 0;\n return (length && strLength < length)\n ? (createPadding(length - strLength, chars) + string)\n : string;\n }\n\n /**\n * Converts `string` to an integer of the specified radix. If `radix` is\n * `undefined` or `0`, a `radix` of `10` is used unless `value` is a\n * hexadecimal, in which case a `radix` of `16` is used.\n *\n * **Note:** This method aligns with the\n * [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`.\n *\n * @static\n * @memberOf _\n * @since 1.1.0\n * @category String\n * @param {string} string The string to convert.\n * @param {number} [radix=10] The radix to interpret `value` by.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {number} Returns the converted integer.\n * @example\n *\n * _.parseInt('08');\n * // => 8\n *\n * _.map(['6', '08', '10'], _.parseInt);\n * // => [6, 8, 10]\n */\n function parseInt(string, radix, guard) {\n if (guard || radix == null) {\n radix = 0;\n } else if (radix) {\n radix = +radix;\n }\n return nativeParseInt(toString(string).replace(reTrimStart, ''), radix || 0);\n }\n\n /**\n * Repeats the given string `n` times.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to repeat.\n * @param {number} [n=1] The number of times to repeat the string.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {string} Returns the repeated string.\n * @example\n *\n * _.repeat('*', 3);\n * // => '***'\n *\n * _.repeat('abc', 2);\n * // => 'abcabc'\n *\n * _.repeat('abc', 0);\n * // => ''\n */\n function repeat(string, n, guard) {\n if ((guard ? isIterateeCall(string, n, guard) : n === undefined)) {\n n = 1;\n } else {\n n = toInteger(n);\n }\n return baseRepeat(toString(string), n);\n }\n\n /**\n * Replaces matches for `pattern` in `string` with `replacement`.\n *\n * **Note:** This method is based on\n * [`String#replace`](https://mdn.io/String/replace).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category String\n * @param {string} [string=''] The string to modify.\n * @param {RegExp|string} pattern The pattern to replace.\n * @param {Function|string} replacement The match replacement.\n * @returns {string} Returns the modified string.\n * @example\n *\n * _.replace('Hi Fred', 'Fred', 'Barney');\n * // => 'Hi Barney'\n */\n function replace() {\n var args = arguments,\n string = toString(args[0]);\n\n return args.length < 3 ? string : string.replace(args[1], args[2]);\n }\n\n /**\n * Converts `string` to\n * [snake case](https://en.wikipedia.org/wiki/Snake_case).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to convert.\n * @returns {string} Returns the snake cased string.\n * @example\n *\n * _.snakeCase('Foo Bar');\n * // => 'foo_bar'\n *\n * _.snakeCase('fooBar');\n * // => 'foo_bar'\n *\n * _.snakeCase('--FOO-BAR--');\n * // => 'foo_bar'\n */\n var snakeCase = createCompounder(function(result, word, index) {\n return result + (index ? '_' : '') + word.toLowerCase();\n });\n\n /**\n * Splits `string` by `separator`.\n *\n * **Note:** This method is based on\n * [`String#split`](https://mdn.io/String/split).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category String\n * @param {string} [string=''] The string to split.\n * @param {RegExp|string} separator The separator pattern to split by.\n * @param {number} [limit] The length to truncate results to.\n * @returns {Array} Returns the string segments.\n * @example\n *\n * _.split('a-b-c', '-', 2);\n * // => ['a', 'b']\n */\n function split(string, separator, limit) {\n if (limit && typeof limit != 'number' && isIterateeCall(string, separator, limit)) {\n separator = limit = undefined;\n }\n limit = limit === undefined ? MAX_ARRAY_LENGTH : limit >>> 0;\n if (!limit) {\n return [];\n }\n string = toString(string);\n if (string && (\n typeof separator == 'string' ||\n (separator != null && !isRegExp(separator))\n )) {\n separator = baseToString(separator);\n if (!separator && hasUnicode(string)) {\n return castSlice(stringToArray(string), 0, limit);\n }\n }\n return string.split(separator, limit);\n }\n\n /**\n * Converts `string` to\n * [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage).\n *\n * @static\n * @memberOf _\n * @since 3.1.0\n * @category String\n * @param {string} [string=''] The string to convert.\n * @returns {string} Returns the start cased string.\n * @example\n *\n * _.startCase('--foo-bar--');\n * // => 'Foo Bar'\n *\n * _.startCase('fooBar');\n * // => 'Foo Bar'\n *\n * _.startCase('__FOO_BAR__');\n * // => 'FOO BAR'\n */\n var startCase = createCompounder(function(result, word, index) {\n return result + (index ? ' ' : '') + upperFirst(word);\n });\n\n /**\n * Checks if `string` starts with the given target string.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to inspect.\n * @param {string} [target] The string to search for.\n * @param {number} [position=0] The position to search from.\n * @returns {boolean} Returns `true` if `string` starts with `target`,\n * else `false`.\n * @example\n *\n * _.startsWith('abc', 'a');\n * // => true\n *\n * _.startsWith('abc', 'b');\n * // => false\n *\n * _.startsWith('abc', 'b', 1);\n * // => true\n */\n function startsWith(string, target, position) {\n string = toString(string);\n position = position == null\n ? 0\n : baseClamp(toInteger(position), 0, string.length);\n\n target = baseToString(target);\n return string.slice(position, position + target.length) == target;\n }\n\n /**\n * Creates a compiled template function that can interpolate data properties\n * in \"interpolate\" delimiters, HTML-escape interpolated data properties in\n * \"escape\" delimiters, and execute JavaScript in \"evaluate\" delimiters. Data\n * properties may be accessed as free variables in the template. If a setting\n * object is given, it takes precedence over `_.templateSettings` values.\n *\n * **Note:** In the development build `_.template` utilizes\n * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl)\n * for easier debugging.\n *\n * For more information on precompiling templates see\n * [lodash's custom builds documentation](https://lodash.com/custom-builds).\n *\n * For more information on Chrome extension sandboxes see\n * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval).\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category String\n * @param {string} [string=''] The template string.\n * @param {Object} [options={}] The options object.\n * @param {RegExp} [options.escape=_.templateSettings.escape]\n * The HTML \"escape\" delimiter.\n * @param {RegExp} [options.evaluate=_.templateSettings.evaluate]\n * The \"evaluate\" delimiter.\n * @param {Object} [options.imports=_.templateSettings.imports]\n * An object to import into the template as free variables.\n * @param {RegExp} [options.interpolate=_.templateSettings.interpolate]\n * The \"interpolate\" delimiter.\n * @param {string} [options.sourceURL='lodash.templateSources[n]']\n * The sourceURL of the compiled template.\n * @param {string} [options.variable='obj']\n * The data object variable name.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Function} Returns the compiled template function.\n * @example\n *\n * // Use the \"interpolate\" delimiter to create a compiled template.\n * var compiled = _.template('hello <%= user %>!');\n * compiled({ 'user': 'fred' });\n * // => 'hello fred!'\n *\n * // Use the HTML \"escape\" delimiter to escape data property values.\n * var compiled = _.template('<%- value %>');\n * compiled({ 'value': '